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.

3
  • @clcto how will it make any difference? Commented Jul 8, 2014 at 5: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. Commented Jul 8, 2014 at 5: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<MyObj>. Commented Jul 8, 2014 at 5:29

1 Answer 1

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(); 
      // ...  //
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.