is there a way for automatically initializing infinite variables?

Hi.

Is there a way to let the user make any number of variables or class objects without me initializing them first?

For example, I am making 2D billiard game as exercise using SFML and want the player to create the balls by clicking on the place where he wants the ball to be, I want a way for a ball to be created and named "ball_01,ball_02" every time he clicks without me making them one by one.

Other related question is how do I enter these variable in a loop or if statment?

For example, if i want to apply an if statement to check if the value of any of these variables: var1, var2, var3, var4... etc is equal to 0 without writing different if statements for each variable?
Looks like templates might be the answer. I don't know enough about them yet so I can't say much.
Create a vector of objects and add to that.

For example, using some shonky pseudocode:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
vector<ball> theBalls;

while (userIsClickingMouseButton)
{
  // create ball
  ball latestBall ( x_position_from_mouseclick, y_positionposition_from_mouseclick);

  // put it into vector
  balls.push_back(latestBall );
}

...

// loop over all balls in vector, doing something
for (int i=0; i<balls.size(); ++i)
{
  // do something with balls[i]
}
Last edited on
Templates are used for different types of variables e.g. int and long which is not what I'm after.

Interesting way to use vectors. I really should stop thinking vector == direction.

Will try this soon, thank you very much.
I have to say, "vector" is a strange name to give a container.
@Moschops: Great example, as usual from you, sir!

@Houd: Who told you that lie? I use templates for all types of classes!

@LowestOne: Study them for awhile and see if you still feel the same way.
Vectors are definitely the way to go here.
Topic archived. No new replies allowed.