Im trying to set an array of 5 elements each with a class in, im also trying to use a construct with each one, but im a bit phased with how, ive been trying this:
1 2 3
for(int i = 0; i < 4; i++){
Box Square(30,30,20,4,1);
}
But I just get an error, is there another way of doing this?
The error is :
1 2
15 C:\Documents and Settings\Cal\My Documents\cpp\SquareGame Recoded\main.cpp variable-sized object `Square' may not be initialized
15 C:\Documents and Settings\Cal\My Documents\cpp\SquareGame Recoded\main.cpp no matching function for call to `Box::Box()'
The way you are doing it looks like you are calling a constructor repeatedly on the same temporary that is destructed every time you exit the for loop. I think if you want to call the individual custom constructors you have to use new.
Creating a Box inside a loop your first example means the Box is destroyed as soon as the loop exits. Your second example is nonsensical, as you're creating Box Square[i] which treats 'Square' like an array when it's not an array, and then assigns it a pointer (from new), when it's not a pointer.
How to do this depends on how 'Square' is defined.
If you want an array of objects on the stack:
1 2 3 4 5 6 7
Box Square[4] = {
Box(30,30,20,4,1), // assuming you want all 4 to look alike
Box(30,30,20,4,1), // note you cannot put this in a loop, which is why this approach is
Box(30,30,20,4,1), // generally not preferable
Box(30,30,20,4,1) };
// no cleanup necessary
If you want an array of objects on the heap, you can't use a specific ctor (have to use the default), but you can set the properties with some kind of Set function:
1 2 3 4 5 6
Box* Square = new Box[4]; // note: default ctor only
for(int i = 0; i < 4; ++i)
Square[i].Set(30,30,20,4,1); // call a Set function to set them up
// for cleanup:
delete[] Square;
lastly you can have an array of pointers on the stack, where the actual objects are on the heap. This allows you to use a specific ctor, but notice that cleanup is more difficult:
1 2 3 4 5 6 7
Box* Square[4];
for(int i = 0; i < 4; ++i)
Square[i] = new Box(30,30,20,4,1); // specific ctor
// for cleanup
for(int i = 0; i < 4; ++i)
delete Square[i];