I have to use an array of pointers to Objects and I must also pass it as parameter to methods. However the way to do this eludes me. Here is the method I use for the initialization of the elements of the array. When I dereference them in main, their data are not correct (they contain memory addresses). What is the correct way? Might it be false the way I dereference them?
void createSquares(Square* squareArray[]){
PropertySquare PropertySquare1(1,"purple",120);
PropertySquare PropertySquare2(2,"purple",170);
squareArray[1] = &PropertySquare1;
squareArray[2] = &PropertySquare2;
.
.
.
}
In main:
Square *allSquares[22] ;
createSquares(allSquares);
cout<<"ID is: "<<allSquares[1]->getID()<<endl;
cin.get();
As I said the ID is finally a memory address.
Update based on answers:
I have tried this and it does not work as well.It is imperative for me to use polymorphism.
vector<Square*> allSquares;
createSquares(allSquares);
void createSquares(vector<Square*> &squares){
PropertySquare PropertySquare1(1,"purple",120);
PropertySquare PropertySquare2(2,"purple",170);
squares.push_back(&PropertySquare1);
squares.push_back(&PropertySquare2);
}
in main:
for (vector<Square*>::iterator it=allSquares.begin(); it!=allSquares.end();it++){
it->
}
It does not allow me to use the virtual functions of Square since it is abstract.
Any suggestion?
Everything you’re doing is Not Good. It’s tricky to figure out where to begin, so let me start at the end and present The Right Way:
Now to break down your problems:
First off, you are storing the pointers of local variables. Those local variables die at the end of the function scope, and the pointers become dangling. Dereferencing is a program error.
Second, to fix this, you should create dynamic objects:
squareArray[1] = new PropertySquare1(1,"purple",120);However, that is problematic, too. Someone will have to clean up those objects! You could iterate over the array and calldeleteon each element.Third,
22is a “magic number” (because it’s neither0nor1). This should not be hard-coded. If the number really is a compile-time constant, name it somewhere.Fourth, either way, don’t use raw arrays. Either use a
std::arrayif the size is known at compile-time, or astd::vectorif the size is determined at runtime.Fifth, putting it all together, a dynamic container of smart pointers takes care of all your worries. That’s the one presented in my code. The alternative, a static array of smart pointers, wouldn’t use an initialization function at all, but rather it’d be initialized right on the spot: