Robert Cheatham Robert Cheatham - 1 year ago 97
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 Source

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
  ~ClsImpl() = default;

class Cls : public ClsImpl {
  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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download