Page 1 of 1

Dynamic Object Creation

Posted: Sun Oct 31, 2010 3:32 am
by kamokow
Hello there,
I've been using C++ for awhile now but just started with game development kind of recently. I recently ran into a problem when starting to work on a new game, I'm not sure if I'm missing something from basic C++ or I'm just looking at the problem wrong. Basically, I'm not sure how to dynamically create objects when I'm not sure of how many objects I will need (if that makes sense/if I'm using the right terminology).

With things like bullets that I have a set maximum for, I can use an array. For example: I can have a bullet class (lets call it 'bullet') and a player class that has an array like:

Code: Select all

class bullet;

class player{
    //other stuff for player class here
    private:
        bullet bullets[20];
};
But what I want to know is how I would go about doing the same as with bullets, except without having a limit on how many I could have. Using a small array of 20 when I might not fill the entire array isnt really all that detrimental, but when I might have a lot more of a particular object being used I wouldnt want to have a bunch of huge arrays for things that might only have 1 or 2 members used.

So, am I missing something in basic c++ that I should go back and learn? When I've tried Google for this I've come up with nothing helpful so I would assume that my problem is simply missing something that I should know from learning C++ or I'm just looking at this problem in the wrong way. I'm just hoping one of you could point me in the right direction, thanks in advance!

Re: Dynamic Object Creation

Posted: Sun Oct 31, 2010 4:50 am
by Busy_V
I think this is what you're looking for.

Have fun with vector arrays! :mrgreen:
;)

P.S.: You may find this article useful: http://stackoverflow.com/questions/1447 ... of-c-array

Re: Dynamic Object Creation

Posted: Sun Oct 31, 2010 5:00 am
by adikid89
You can do something like this...

Code: Select all

class bullet;

class player{
    //other stuff for player class here
    private:
       vector<bullet*> bullets;
       AddBullet()
      {
          bullet* b = new bullet;
          bullets.push_back(b);
      }
      RemoveBullet()
      {
           //free memory
           delete bullets.back();
           //erase it from the vector
           bullets.pop_back()
      }
};

Re: Dynamic Object Creation

Posted: Sun Oct 31, 2010 1:18 pm
by kamokow
Oh, thanks you guys. I completely forgot about vectors =_=.

Re: Dynamic Object Creation

Posted: Thu Nov 04, 2010 11:18 am
by MrDeathNote
Banned wrote:Content removed by admin.
Someone should delete all hotxxl007's posts and ban the account.

Re: Dynamic Object Creation

Posted: Sun Nov 07, 2010 10:12 pm
by dandymcgee
MrDeathNote wrote: Someone should delete all hotxxl007's posts and ban the account.
Good idea, done.