problem with class

This is a discussion on problem with class within the C++ Programming forums, part of the General Programming Boards category; see my second example... the danger is called a memory leak - if you run the program enough times, theoretically ...

  1. #16
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    see my second example... the danger is called a memory leak - if you run the program enough times, theoretically your system would run out of memory. in the learning stages it's not a big danger, but imagine in a company that keeps the program running all day long...

    basically, just remember that for every new, you need a correspoding delete, and for every new[], you need a delete[]
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  2. #17
    Registered User
    Join Date
    Jul 2005
    Posts
    20
    Thanks alot Major!

    Yup, I know about memory leaks... So this is how they happen? Didn't Windows have some?

    Couldn't you just destroy all pointers in the end of the funktion that uses them, thereby eliminating the problem?

    btw, I don't see new, nor new[] anywhere in your example using refference. I suppose they still have to be destroyed somehow?

  3. #18
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    I'm sorry. that was my first example they were in...

    you could, except in the case where you're constantly creating new ones... for example, take this code for a linked list. you'll notice that new and delete actually occur in loops:
    Code:
    #include<iostream>      //for console I/O
    #include<string>        //for string class
    
    struct node;            //prototyped for linking in itself
    
    struct node             //structure
    {
            std::string data;       //to hold the data
            node*link;              //a pointer to the next one in the list
    };
    
    int main()
    {
            std::string line;       //to hold input
    
            node*head=new node;     //this pointer holds the head of the list
            node*curr=head;         //this is where the work is done
            node*next=head;         //this is to help move down the list
            curr->link=0;           //set the pointer to null to avoid problems
    
            std::cout<<"Enter some lines of text:\n\n";
    
            for(;;)         //semi-infinite loop
            {
                    getline(std::cin,line,'\n');    //get input
    
                    if(line=="")    //if there's no input
                    {
                            curr->data=line;        //put that in the last one
                            break;  //break out of the loop
                    }
    
                    curr->data=line;        //else, put the data in the structure
                    next=new node;          //create a new structure in memory
                    curr->link=next;        //make the pointer point to it
                    curr=next;              //move into it
                    curr->link=0;           //and make that pointer null
            }
    
            curr=head;                      //go to the top of the list
            std::cout<<"You Entered:\n\n";
    
            while(curr->data!="")           //while there's data
            {
                    std::cout<<"> "<<curr->data<<std::endl; //output it
                    next=curr->link;        //save the location of the next one
                    curr->link=0;           //nullify this link
                    delete curr;            //delete this one
                    curr=next;              //move into the next one
            }
            delete curr;    //delete the last one (with no data in it)
    
            return 0;
    }
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  4. #19
    Dae
    Dae is offline
    Deprecated Dae's Avatar
    Join Date
    Oct 2004
    Location
    Canada
    Posts
    1,034
    If you only have one class for all the data, why not just declare your object outside of everything, so you will not have to pass reference to the class. Why would you need to pass a reference to it, its not like there are going to be 1-5 players, or 1-1000000 in the case of Warcraft. I dont believe this has any negative effects, but if it does, you could pass the reference, which I'll show in the next post a different version of this.

    Code:
    #include <iostream>
    
    using namespace std;
    
    typedef unsigned short int USHORT; //makes your own variable, USHORT, which is an unsigned short int
    
    class Player_Stats
    {
    private:
      USHORT itsLevel;
    
    public:
      Player_Stats():itsLevel(0) {} //constructor, initializing itsLevel variable to 0
    
      USHORT GetLevel() const { return itsLevel; }
      void SetLevel(USHORT level) { itsLevel = level; }
    
    };
    
    Player_Stats pStats;
    
    void aFunction() {
      cout << pStats.GetLevel() << endl; //output: 0
      pStats.SetLevel(10);
      cout << pStats.GetLevel() << endl; //output: 10
    }
    
    int main()
    {
      aFunction();
    
    }
    Like said above, you make your variables in the class private, and make functions to return/set them if necessary in the public, this is if you plan on using them outside that class. You could always do most of your game using all classes, functions of the class, derived from the class, friend of the class, etc. as mentioned above.
    Last edited by Dae; 07-10-2005 at 02:24 AM.
    Warning: Have doubt in anything I post.

    GCC 4.5, Boost 1.40, Code::Blocks 8.02, Ubuntu 9.10 010001000110000101100101

  5. #20
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    generally you should try not to create things globally... if you really wanted to, however, you could also do this:
    Code:
    class Player_Stats
    {
      private:
        USHORT itsLevel;
    
      public:
        Player_Stats():itsLevel(0) {} //constructor, initializing itsLevel variable to 0
    
        USHORT GetLevel() const { return itsLevel; }
        void SetLevel(USHORT level) { itsLevel = level; }
    
    } pStats;
    also, I just noticed that your class was missing a semi-colon.
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  6. #21
    Dae
    Dae is offline
    Deprecated Dae's Avatar
    Join Date
    Oct 2004
    Location
    Canada
    Posts
    1,034
    Passing a reference OF the object of the stats class:

    Code:
    #include <iostream>
    
    using namespace std;
    
    typedef unsigned short int USHORT; //makes your own variable, USHORT, which is an unsigned short int
    
    class Player_Stats
    {
    private:
      USHORT itsLevel;
    
    public:
      Player_Stats():itsLevel(0) {} //constructor, initializing itsLevel variable to 0
    
      USHORT GetLevel() const { return itsLevel; }
      void SetLevel(USHORT level) { itsLevel = level; }
    
    };
    
    void aFunction(Player_Stats& pStatsCopy) /* argument takes the memory location to an object of Player_Stats class */
    {
      cout << pStatsCopy.GetLevel() << endl; //output: 0
      pStatsCopy.SetLevel(10);
      cout << pStatsCopy.GetLevel() << endl; //output: 10
    }
    
    int main()
    {
      Player_Stats pStats;
    
      aFunction(pStats);
    
      cin.get();
    }
    Warning: Have doubt in anything I post.

    GCC 4.5, Boost 1.40, Code::Blocks 8.02, Ubuntu 9.10 010001000110000101100101

  7. #22
    Dae
    Dae is offline
    Deprecated Dae's Avatar
    Join Date
    Oct 2004
    Location
    Canada
    Posts
    1,034
    Quote Originally Posted by major_small
    generally you should try not to create things globally... if you really wanted to, however, you could also do this:
    Code:
    class Player_Stats
    {
      private:
        USHORT itsLevel;
    
      public:
        Player_Stats():itsLevel(0) {} //constructor, initializing itsLevel variable to 0
    
        USHORT GetLevel() const { return itsLevel; }
        void SetLevel(USHORT level) { itsLevel = level; }
    
    } pStats;
    also, I just noticed that your class was missing a semi-colon.
    Declaring Class Player_Stats { } pStats; is exactly the same thing as declaring it later (its global either way), its only seperated I think.

    Yeah I just noticed that semi-colon too, and was about to edit when I saw this post.
    Warning: Have doubt in anything I post.

    GCC 4.5, Boost 1.40, Code::Blocks 8.02, Ubuntu 9.10 010001000110000101100101

  8. #23
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    nono I know it's still global, I was just pointing it out to you in case you didn't know you could do it that way.
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  9. #24
    The N00b That Owns You!
    Join Date
    Jul 2005
    Location
    Canada!
    Posts
    178
    Quote Originally Posted by muggizuggi
    Hi there, I'm new.

    I search the c++ forum for "class", pick the first topic, and what do I find?
    Someone with the exact same problem I am having!

    I am writing a texst/rpg-type game, and I would like a funktion to be able to access the public variables of an object.

    Now, I think Daved said that it could be done, by passing a refference to the object, that had to be deleted later, and is dangerous.
    Ehh, how dangerous is it? And What could it possibly do?

    Is there perhaps a safer way, to only let funktions access the public methods of the object? Or would that need the dreaded refference too?

    Thank you in advance!
    i like this kid he uses search!

  10. #25
    Registered User
    Join Date
    Jul 2005
    Posts
    20
    Ok Major, I slept on it and I think I see your point.
    Doing it like that (creating and deleting pointers/references all the time) can get messy, and may also take its toll on the CPU, once I get to more advanced stuff? Or is that not how things work?

    And Dae, thanks for trying to help out!
    That was exactly what I wanted when I came here, but since it seems to be considered bad practice, maybe I should try an other route?

    My original plan was to have one class called "human", and then create an object of that for each character in the game, including the player.

    So what if I made the "human" class, and then a "player" sub class to extend the "human" class. Then I could keep all the things that could happen with the player as methods of that class.

    Would that be the clever, expandable, reusable OOP way of the wise?

  11. #26
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    well, you'll need references and pointers, and in this case you kinda have to use them (unless you want to use Dae's approach), but some ways are just easier than others. like in my case, neither are really much 'better' than any other (even though that's debatable), some are just easier on the brain to think about.

    and about the player and human subclass, you should look into inheritance. that's exactly what you want there. basically, you could create a human class, and a derived player class that, like you mentioned, extends the human base class. the player class would have all or most of the methods from the human class, plus some of it's own.
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  12. #27
    Dae
    Dae is offline
    Deprecated Dae's Avatar
    Join Date
    Oct 2004
    Location
    Canada
    Posts
    1,034
    Quote Originally Posted by muggizuggi
    And Dae, thanks for trying to help out!
    That was exactly what I wanted when I came here, but since it seems to be considered bad practice, maybe I should try an other route?

    Would that be the clever, expandable, reusable OOP way of the wise?
    It isnt bad practice, in this case. The fact that your entire game revolves around your Player makes pure sense that you would create your Player class object globally. Using either method will not result in extra memory used or problems, but makes the code read differently.

    However, even though I suggested that.. I agree with Major, I would use references (or pointers) just because it makes the code easier to read, so anyone reading it knows where things are coming from. I believe the reason I even recall using that method is because I did win32 API programming when I didnt know how to work with multiple files, OOP, or inheritance well enough that I had global objects and used 'externs'.
    Warning: Have doubt in anything I post.

    GCC 4.5, Boost 1.40, Code::Blocks 8.02, Ubuntu 9.10 010001000110000101100101

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Mesh Class Design problem
    By sarah22 in forum Game Programming
    Replies: 2
    Last Post: 05-20-2009, 05:52 AM
  2. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 09:18 PM
  3. Class design problem
    By h3ro in forum C++ Programming
    Replies: 10
    Last Post: 12-19-2008, 09:10 AM
  4. My Window Class
    By Epo in forum Game Programming
    Replies: 2
    Last Post: 07-10-2005, 03:33 PM
  5. Replies: 3
    Last Post: 12-03-2001, 01:45 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21