Creating objects

I've programmed c++ for a while, but got on a problem which I don't know to solve.

Let's say I have an class called Bird.

On my main method, when my program is running I want people to create Birds, so let's say when the user press B, a new bird is created like:

1
2
3
if(key='B'){
  Bird b("blue");
}


How do I manage to create multiple birds without overwriting the first one? Do I need to declare like:

1
2
3
Bird b1("name1");
Bird b2("name2");
...


Which is impossible to do while the program is running.

How to solve this problem?
Put them into an std::vector or another container:

1
2
3
4
5
std::vector<Bird> birds;
if(key == 'B') {
    birds.push_back(Bird()); //add a new bird
}
//... 
On a related note, in this code:

1
2
3
4
if(key='B'){
  Bird b("blue");
}
// Bird object 'b' ceases to exist here 


the Bird object 'b' you created on the stack will be destroyed as soon as you leave the scope in which it was made. If you're going to create objects that must exist beyond the scope in which they were created, you can make them using new (and you will then be responsible for destroying them with delete).

Using a vector or other such container as firedraco suggests will keep you from having to manage this yourself.
Topic archived. No new replies allowed.