Question

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.

Was it helpful?

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.

OTHER TIPS

Local variables are created on the call stack. Which means that these variables are always destroyed when the function finishes.

It is unclear how do you retrieve the Rectangle object and how do you handle the array of Shape object pointers from the code you pasted. But you probably need two things:

  1. Your Rectangle must not be on the stack, but it must be allocated on the heap.
  2. You need access to the shape array on all places, where you want to access it.

I would suggest you to create a class which will wrap your functions and have Shape objects instantiated and removed dynamically using new and delete keywords. I believe this is the easiest way. Something like this should work:

/* interface */

class Example
{
     Shape *shape[3];

     public:

     Example();
     ~Example();

     void create();
     void process();
};

/* implementation */

Example::Example() {}

Example::~Example()
{
    delete shape[0];
}

void Example::create()
{
    shape[0] = new Rectangle();
}

void Example::process()
{
    shape[0]->print();
}

/* main */

int main()
{
    Example example();
    example.create();
    example.process();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top