5

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.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • @clcto how will it make any difference? – Bryan Chen Jul 08 '14 at 05:28
  • 2
    @clcto Passing in a pointer versus a reference is not an issue. Pointers *and* references do NOT get sliced. Consider pointers and references "non-slicable". The slicing happens on the statement with the `new` call. –  Jul 08 '14 at 05:28
  • 1
    As far as I know, you have two main options, have a virtual method called `clone()` or be able to give some sort of ownership of `obj` to `myFunc()`, perhaps by using a `shared_ptr`. – Bill Lynch Jul 08 '14 at 05:29

1 Answers1

6

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(); 
      // ...  //
  }
Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205