Search code examples
c++arraysobject-lifetime

How do I use a pointer to an object from one function in another function?


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.


Solution

  • 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::vector you should start allocating (in your main) your vector as

        std::vector<Shape*> shape(3);
    

    Doing so you can access your dynamically bound vector entries as

        shape[0]->process();
    

    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

        std::vector< std::tr1::shared_ptr< Shape > > shape(3);
    

    ?

    Doing this way, the smart pointer std::tr1::shared_ptr will free the memory for you when the pointed Shape object goes out of scope.

    Moreover, in this setting, you should allocate Shape-type objects as

         shape[0] = std::tr1::shared_ptr< Shape >(new Rectangle);
    

    to properly create the smart pointer you need.

    Finally, the vector shape should be passed by reference (or const reference) to functions using it.