Copy Assignment Operator
Is when you make one object equal to another. Both already exists. Remember to always check for self assignment to make it correct.
class Test {
public:
Test() {};
Test(const Test& t) {
cout << "Copy constructor called " << endl;
};
Test& operator=(const Test& t) {
cout << "Assignment operator called " << endl;
return *this;
};
};
Copy Constructor vs. Copy Assignment Operator
The fields are already initialized. Therefore, we need to do some cleanup. On the other hand, in case of a Copy Constructor, fields are not initialized. So we don’t worry about cleanup.
A a;
A c;
A b = a; // Calls copy constructor
a = c; // Calls copy assignment constructor, since both objects are initialized already
Strategies for Implementation
Method 1: (the one I will be using?)
- check for self assignment:
if(this != &other)
- delete the old resource: delete
this->next
- allocate new resource
this->next = new Object{ *other.next }
#4 return*this
Method 2
- Allocate temporary object on STACK: Obj temp(rhs)
- SWAP the internal data with “this”: swap(temp.pointer, this→pointer)
- return
*this
(destructor will clean up the old resources, which got swapped into temp object)