I have a pointer to an object which i will be using in one method. but i need to use the same pointer again in another method how can i achieve this without declaring as global object. This is part of my dynamic biding achievement
Shape is the parent class and the Rectangle is the child class.
int main(){
switch (choice){
case 1:
create();
break;
case 2:
process();
break;
}
}
create(){
Shape *shape[3];
shape[0]=&objRectangle;
}
process(){
for(int i=0;i<3;i++){
shape->print; // I want to acchieve like this.
}
Now i cant do this cause, the shape object is gone once it exits the create process.
Please assist.
I would suggest, as others do, to let the library manage the memory for you.
In order to be able to use dynamic binding and
std::vectoryou should start allocating (in your main) your vector asDoing so you can access your dynamically bound vector entries as
The bad thing is that you still have to manage the memory pointed by vector entries (they are just C pointers, in fact). Hence, why don’t you consider doing
?
Doing this way, the smart pointer
std::tr1::shared_ptrwill free the memory for you when the pointedShapeobject goes out of scope.Moreover, in this setting, you should allocate
Shape-type objects asto properly create the smart pointer you need.
Finally, the vector
shapeshould be passed by reference (orconstreference) to functions using it.