How to create a user-determined number of class objects at runtime?

Dec 27, 2009 at 11:39pm
I have a class set up, Vehicles. I have the constructor and variables set up correctly, and I can properly create an object of this class through code, such as:

Vehicle minivan;

It naturally follows that I can create multiple objects of this class in code, such as:

Vehicle minivan;
Vehicle truck;
Vehicle car;

However, what I cannot figure out is how to allow the user to determine how many objects he wants to create without specifying a large number of them in code and hoping he doesn't want to create more than that number.

My program allows a user to create a vehicle, specifying the name and various features. After creation, the user is brought back to the main menu and has the option of creating another vehicle in the same manner. The user is able to do this as many times as he fancies, but I cannot work out a way to create a new object on the fly without having it predefined in the code, such as:

Vehicle car1;
Vehicle car2;
Vehicle car3;
...
Vehicle car999;

I know the following code isn't even close to legit, but I'm looking for a solution that would function in this manner. Please ignore the fact that this isn't even close to real code, and just focus on the intention of what I have here:

Vehicle car[x];
Create another vehicle (y/n)? Y
...
Vehicle car[x+1];
...
car[x].wheels = 4;

Is this impossible? Or perhaps I simply haven't gotten far enough along in my self-teachings to reach a specific function that allows me to accomplish this?
Dec 27, 2009 at 11:43pm
You can use a list or a deque
http://www.cplusplus.com/reference/stl/list/
http://www.cplusplus.com/reference/stl/deque/
They are both containers which can easily expand their sizes calling push_back
http://www.cplusplus.com/reference/stl/deque/push_back/
The deque also has the subscripting operator [ square brackets ] overloaded
Dec 27, 2009 at 11:52pm
Thanks a lot for the quick reply, looks like I have another topic to tackle. A quick glance tells me this is exactly what I was looking for.
Dec 28, 2009 at 5:54am
Or you could learn about pointers and dynamic memory-it'll help you even in cases where you can't use the STL. (I.E. a class at school, or something with an extremely small amount of memory)
Dec 28, 2009 at 12:22pm
If you have to resize an array, dynamic allocation or vectors aren't efficient as they often require a complete reallocation of all the memory
Dec 28, 2009 at 5:19pm
But if you only need to create an array with an unknown size, than it's fine.
Topic archived. No new replies allowed.