Robert Cheatham Robert Cheatham - 4 months ago 10
C++ Question

C++ call default copy assignment operator from overloaded copy assignment operator

I want to use the default functionality of the copy assignment operator but be able to do some additional tasks as part of the operation. So the basics form would look like this:

class Test
{
void operator=(Test& that)
{
*this = that; //do the default copy operation
this->foo() //perform some other tasks
}
};


This could easily be done by creating a copy() function but it would be nice to preserve the cleanliness of the "=" operation.

Answer

You could use a base implementation class and delegate to the base operator= from the subclass

// Fill this class with your implementation.
class ClsImpl {
  // some complicated class
 protected:
  ~ClsImpl() = default;
};

class Cls : public ClsImpl {
 public:
  Cls& operator=(const Cls& other) {
    if (this == &other) { return *this; }
    // assign using the base class's operator=
    ClsImpl::operator=(other); // default operator= in ClsImpl
    this->foo(); // perform some other task
    return *this;
  }
};