ruben
ruben

Reputation: 1750

Copy referenced object and call virtual method C++

Here MyLineShape object b is passed by reference to this function (in MyCustomWidget class): and myShape is a Shapes pointer.

void MyCustomWidget::setDrawingObject(Shapes &b){
   myShape = &b;
   myShape->setPoint1();
}

It works i.e it calls myShapes setPoint1() method. But when in other part of this MyCustomWidget class I try to use

myShape->setPoint1();

the program crashes. Maybe this is because of scope? setPoint1() is a virtual function as different shape classes implements it separately. So what I am trying to do is in setDrawingObject function to tell which object it has received from reference and make a copy of that type of object for later use in this class's other function call. How to do that?

Upvotes: 1

Views: 66

Answers (1)

Barry
Barry

Reputation: 302807

It sounds like you just have a dangling pointer. Whatever object you're calling setDrawingObject is getting destroyed while you still have a pointer to it. There are two common approaches to solving this problem. First, just use shared_ptr:

void MyCustomWidget::setDrawingObject(shared_ptr<Shapes> b) {
   myShape = b;
   myShape->setPoint1();
}

The second would be to add a virtual clone() member function to Shapes that you would all here to make a copy. So something like:

void MyCustomWidget::setDrawingObject(Shapes& b) {
    myShape.reset(b.clone());  // myShape is a unique_ptr<Shapes>
    myShape->setPoine1();
}

Either way, avoid having myShape simply be a Shapes*.

Upvotes: 2

Related Questions