This is a problem I've had before but have always dismissed. It has caused several personal projects to be ignored and cancelled due to my inability to find a way around it.
Basically, my problem is that I'm not sure how to have a program create more instances of a class based upon a number given by a user. My current use is in a game akin to the Dungeon Crawler practice project somewhere in this forum but it's going to have a level editor. So when the user wants to have 5 monsters, how do I create those 5 during runtime?
I was planning on holding all of the monsters/obstacles/etc in a vector but I'm more confused on how to initialize the dynamic amount of monsters/obstacles/etc beforehand.
@Vins3Xtreme
I haven't looked at new for a very long time. I guess it's time to go back and see how it can help. Thanks.
With a std::vector, its size can grow on cue; therefore, it can grow during run-time. Also, you don't have to allocate any memory for it to function; that's do automatically. The std::vector allocates, or reserves, a region of memory initially for new elements. When the reserved memory is exhausted, a new region of memory is allocated, then contents of the old vector are transferred over to the new vector.
I feel your pain, std::vector/std::list is what you are looking for.
Just create a vector of the class you need to store and add or remove as many as you need.
So you can simply use the same instance of a class (the Monster named dragon) over and over again despite being a single instance? Does that mean all Monsters named dragon will have the same data and not looked at as individuals?
So you can simply use the same instance of a class (the Monster named dragon) over and over again despite being a single instance?
Yes, because when you push back an instance into the container, it creates a copy of that instance.
Does that mean all Monsters named dragon will have the same data and not looked at as individuals?
You can create multiple versions of dragons.
1 2 3 4 5 6 7 8 9 10 11 12 13
class Monster
{
Monster(string nam, int hp,)
{
name = nam;
health = hp;
}
string name;
int health;
}
Monster dragon1("Dragon",20);
Monster dragon2("Dragon",30);
The variable names here are different but they are still "Dragons."