Avoiding Object Slicing C++

c++, object-slicing

Solution

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(); 
      // ...  //
  }

Problem

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.

Original source