user245019
user245019

Reputation:

Avoiding Object Slicing C++

I have an issue where I'd like to copy an object, but want to avoid slicing it.

DerivedObj derivedObj;
myFunc(derivedObj);

void myFunc(MyObj &obj)
{
   MyObj *saveForLater = new MyObj(obj); // slices my object
   // ...  //
}

Is there a way to get around this? I do need to make a copy because the original object will have left scope before it is required.

Upvotes: 5

Views: 1071

Answers (1)

Andrew Shepherd
Andrew Shepherd

Reputation: 45252

If your constraints allow it, you could add a virtual Clone method.

 class MyObj
 {
      public:
           virtual MyObj* Clone() const = 0;
 };

 class DerivedObj : public MyObj
 {
      public:
          virtual MyObj* Clone() const 
           {
                return new DerivedObj(*this);
           }
 };




 void myFunc(MyObj &obj)
 {
      MyObj *saveForLater = obj.Clone(); 
      // ...  //
  }

Upvotes: 6

Related Questions