Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 870
Robert Cheatham Avatar asked Oct 19 '22 04:10

Robert Cheatham


1 Answers

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;
  }
};
like image 144
Ryan Haining Avatar answered Nov 15 '22 05:11

Ryan Haining