Martin Pohorský
Martin Pohorský

Reputation: 451

Instances of the same object in C++ (game programming)

I was wondering how to create multiple instances of the same object in C++. I have an example. Let's say I am creating a simple action game and I have an object called "Bullet". If I hit f.e. a CTRL key it causes a gunfire. So I create an instance of Bullet. The instance dies when the bullet hits something or get out of the window. But what if I have f.e. something like machine gun. It can fire many bullets in a row. So I have to create many instances of Bullet, but how can I do that? Should I at the beginning make a pointer like this

Bullet *pointer;

Then when I want to create an instance of the bullet I allocate a space in memory for one "bullet". And when I want to create next bullet I allocate more space and so on. But when a bullet "dies" I got a dead space in memory...

So I do not know how to handle this situation. I am new to OOP. I have programmed in C and now I want to learn C++ through the game programming (it is quite fun) :-). Thanks for the answers!

Upvotes: 1

Views: 262

Answers (1)

Shoe
Shoe

Reputation: 76240

Simply use std::vector<Bullet> bullets to store all of your bullets. You are going to need all those objects anyway and std::vector will:

  • amortize appending new objects
  • allow you to shrink_to_fit if at any point the vector became too large
  • allow you to reserve a certain number of elements at the beginning, effectively creating an empty pool of objects
  • keep all your objects contiguously, making everything very efficient

You may also want to try std::unordered_map which has almost constant time insertion and removal.

Upvotes: 2

Related Questions