0

From various posts including this one I have noticed the copy and swap idiom however I am not sure how to implement this code when it comes to derived classes. The code there is specified as

dumb_array& operator=(dumb_array other) // (1)
{
    swap(*this, other); // (2)

    return *this;
}

I understand that whenever a custom assignment operator is defined in a derived class then it is the responsibility of that methods to call the assignment operator of the base class. How would I go about optimally calling the assignment operator of the base class in this case. This is my attempt

dumb_array& operator=(dumb_array other)
{
    swap(*this, other); 
    baseclass::operator= other; //Suppose base class has assignment operator resembling this
    return *this;
}

My understanding is that if we call the base class assignment operator from the derived class then the copy constructor (because the parameter is value type) will be called twice (one for derived and then again for base)( and this is only if if it was a single chain of inheritance) what would be the optimal way to call the copy assignment operator of the derived class along with the base class ? Will we need to make changes to the swap method ?

Community
  • 1
  • 1
MistyD
  • 13,289
  • 28
  • 108
  • 198

3 Answers3

0

You are mixing two idioms that operate in different context.

swap call is ok to swap something that is a POD or similar like that.

On the other hand when you have a class hierarcy that may be not the right thing, and here the the second approach (with relying on the base class knowing how to swap itself may be more appropriate).

But there is another point worth mention: overriding operator= is typical of classes having value semantic, while when you start dealing with derived classes (and maybe working on objects holding just a pointer to base class) then this is no longer the case (and you rather clone() objects instead of copying them)

marom
  • 4,944
  • 8
  • 14
0

There's no need to call baseclass::operator= in the operator= of derived class in this scenario. When you pass the argument by value, you already get a valid copy produced by copy constructor of derived class, which in particular should invoke copy constructor of the base class. So your initial code is perfectly valid for derived class as well.

Anton Savin
  • 38,277
  • 8
  • 49
  • 82
0

Using the copy and swap idiom for assignment operator with derived classes

This is not something you should do (due to the slicing problem). If your class has polymorphic behavior, usually you will not need assignment - you will need to duplicate values, keeping in mind polymorphic behavior. This means cloning, defined at the level of the base class and implemented in your entire hierarchy.

Community
  • 1
  • 1
utnapistim
  • 24,817
  • 3
  • 41
  • 76