0
Creating multiple classes?
How could one go about creating multiple objects without assigning each an individual name? If I want to create a game like zombie tsunami, how would I create each of the objects without storing them all into memory permanently? I read that it may have something to do with vectors. With telling me what to do, could you offer an explanation also? This would be very helpful, as I am new to programming, yet I want to pursue a job in it. Thank you very much.
2 Réponses
+ 1
I would really suggest looking at all different kinds of c++ containers to find what exactly you need, as far as memory and access to each element goes. Here is where I learned everything I now know about them: http://www.cplusplus.com/reference/
If you look to the left when you click this link, there's an extendable plus symbol for 'containers' where you will find all the information and more (sometimes overwhelming at first) on all kinds of containers, including vectors.
I think that what you might be looking for is a for loop that instantiates new zombie objects. With a vector, you could then add each of them into the container like this:
#include <vector>
vector<Zombie*> zombieContainer;
for (int i = 0; i < nZombiesWanted; i++) {
Zombie* pZombie = new Zombie();
zombieContainer.push_back(pZombie);
}
The only catch with using the 'new' keyword like this is that you HAVE to remember to use the 'delete' keyword down the line or you will have memory leaks. And technically the example I gave you is not a vector of objects, but a vector of object pointers. And accessing an element in a vector is as easy as array syntax: zombieContainer[2].
0
you could create an array of objects. each array index would be a different object. and you can access them respectively. you could use a dynamic array to push these objects onto. this way you could delete an object if needed. a vector is a c++ built in ADT that acts as a dynamic array.