Copy Assignment Operator

When you make one object equal to another.

class Test {
    Test() {};
    Test(const Test& t) {
        cout << "Copy constructor called " << endl;
    Test& operator=(const Test& t) {
        cout << "Assignment operator called " << endl;
        return *this;

Use the Copy-and-Swap Idiom to implement this.

Notice that this is simply an operator overload on operator=!

Copy Constructor vs. Copy Assignment Constructor

In copy assignment operator, you already have your fields initialized. Therefore, you need to do some cleanup. On the other hand, for copy constructor, your fields aren’t initialized, so you don’t need to worry about cleanup.

A a;
A aa;
A b = a; // Calls copy constructor
a = aa; // Calls copy assignment constructor, since both objects are initialized already

Some Strategies

Method 1 (the one I will be using)

  1. check for self assignment: if(this != &other)
  2. delete the old resource: delete this->next
  3. allocate new resource this->next = new Object{ * }
  4. return *this

Method 2

  1. Allocate temporary object on STACK: Obj temp(rhs)
  2. SWAP the internal data with “this”: swap(temp.pointer, thispointer)
  3. return *this (destructor will clean up the old resources, which got swapped into temp object)