Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Having many objects

Tags:

c++

object

class

So, I have a question about C++. Let's say that I have an enemy class for a game. I want to be able to have (in theory) an infinite amount of enemies in my game. So I would have to have multiple instances of each class, and I would need to be able to access these separately. Would I have to have an array of enemy objects with an unlimited amount of space for the array, and I would use the new and delete operator to create and remove enemies in the array? Then I would need a variable to hold the number of enemies, right?

like image 354
Toromak Avatar asked Jun 12 '26 01:06

Toromak


1 Answers

Use std::vector. It will automatically allocate more memory as needed.

There are also other containers in the standard library that will automatically allocate memory when needed like for example std::list, std::set or std::map. These containers may be more suitable in special cases, however std::vector is usually the best choice. It all depends on the implementation details.

You can use it like this:

#include <vector>

struct Enemy {
    //...
}

std::vector<Enemy> v;

Enemy e1, e2;
v.push_back(e1);
v.push_back(e2);

std::cout << "First enemy in vector: " << v[0];
like image 92
Felix Glas Avatar answered Jun 14 '26 13:06

Felix Glas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!