# Calling an arbitrary number of classes - C++

This topic is 2995 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I know this question is the n00b of the n00bs, but since I'm having no joy on google, I thought I'd ask here. If I want to generate an unknown number of balls, for instance, that have a class associated with them, how do I do that? Until now I've been naming individual instances like so: ball ball1; How can I call a previously unspecified number of these classes, on demand? So, for instance, when a user clicks, a new instance of the class ball is created? Now, I appreciate that the information is probably out there somewhere, so if you don't feel like giving an explanation to the whole thing, just tell me what I need to google and I'll get on with that. ;) The question is posted here 'cause I'm having no luck doing it myself. Cheers [Edited by - icilian fenner on December 5, 2009 7:47:27 AM]

##### Share on other sites
I only recently learnt about the standard template library's containers.
You can check them out here: http://www.cplusplus.com/reference/stl/
For a system where balls will be added and or removed all the time, I would suggest a list (but I'm new to them, I could be wrong...)

##### Share on other sites
You store them in a container. The simplest container is an array, but an array has an arbitrary upper limit on the number of objects it can store. Consider using the Standard C++ Library type std::vector<>, which is a dynamic array to store your objects.

##### Share on other sites
:D You guys are magic. Thanks a lot! I'll read up on that and try to implement it now ;)

##### Share on other sites
Okay, I've had a crack at this, and am having a newb frustration time. Darn teething pains.

How am I to give a specific (but modifiable) name to the classes? I appreciate how to store using a vector (thank you very much for turning me on to that), but I'm still a little lost as to how to generate unique names for each of my instances?

I may well be thinking of this the wrong way, but I'm having one of those blank 'head against the wall' moments.

##### Share on other sites
You can use the [] operator to get access to each value in a vector. Remember the first value is number 0 (not number 1)
std::vector<ball> balls;balls.resize(3);//make 3 balls//get some hard-coded references to these ballsball& ball_1 = balls[0];ball& ball_2 = balls[1];ball& ball_3 = balls[2];ball_1.BounceOff( ball_2 );ball_3.DoSomething();//loop over every ballfor( int i=0; i<balls.size(); ++i ){  ball& ball_i = balls;  ball_i.DoSomething();}

##### Share on other sites
:) hodgeman, I think I see what you're getting at. I didn't realise that you could use a class as the 'type' inside <>. :D! wonderful.

• 12
• 10
• 11
• 18
• 13