-
Class Instantiation
Hope someone can help me.
I need to create a user specified number of differntly named instances of a object, in a loop for example.
Just in case I havent explained clearly:
User inputs the number of boxes they want
program then creates this number of boxes from the class Container
Container box1();
container box2();
and then some of the boxes get stuff added to them.
however since i dont know how many boxes are going to be created, i must have a loop that creates each box, named similarly as above for as many boxes as the user requires.
-
Use either:
1) A linked list of dynamically allocated objects.
2) Since 1) is a pretty advanced topic, you can make a dynamic array containing the objects, something like this:
Code:
//Create a pointer
Container* ConPtr;
...User input
//Allocate memory
ConPtr = new Container[NrOfObjects];
//Check if the allocation was successful
if(ConPtr != NULL)
{
for(int i=0; i<NrOfObjects; i++)
{
//Since the constructor doesn't work on dynamically allocated
//objects, you have to run a similar function on them
ConPtr[i].SetInitialvalues();
}
...Do whatever you want
//Deallocate the allocated memory
delete[] ConPtr;
}
-
As for the initial question: You can't create variable names after the program is compiled. In fact, once your program is compiled, function names no longer even exist. Remember, C++ isn't an interpreter language, so once it's compiled, the code (and variable names are part of the code) can no longer change. You'll just have to make an array of the things.
Also, I have a question for Magos:
//Since the constructor doesn't work on dynamically allocated
//objects, you have to run a similar function on them
Hm? Do you mean that if I code
class Aclass{Aclass(); ~Aclass();};
Aclass *aclass;
aclass=new Aclass;
the constructor is NOT called? Weird! So when ís the constructor called?
-
Sorry, my fault.
The constructor is actually called even in dynamic allocations (Made some tests on this one).