Copy Assignment CSCE 121
Overload ‘=‘ Operator ‘=‘ is the assignment operator Allows class to perform expected deep copy behavior
Using Copy Assignment MyClass object1, object2; // modify object 1 object2 = object1;
Declaration ClassName& operator=(const ClassName& source); a = b; a.operator=(b);
Definition Prevent a memory leak! ClassName& Classname::operator=(const ClassName& source) { if (this != &source) { // don’t self assign // Delete old data // Allocate new memory // Copy data } return *this; Prevent a memory leak!
Copy Assignment vs. Copy Constructor Return: reference to self Function name: operator= Parameter: const reference to source object of same type Check for self-assignment Delete old data Allocate new memory Copy data from source Return: None (all constructors) Function name: ClassName Parameter: const reference to source object of same type Allocate new memory Copy data from source If we compare the copy assignment operator to the copy constructor, we see first of all that they take the same parameter: a const reference to the source object. And it we look at what they do, we see that the copy constructor is the same as the copy assignment operator, minus a couple of missing steps that aren’t needed. Now why would we not need to check for self-assignment and delete old data? ... Because the object is just being created, so there’s nothing to delete yet, and it can’t be equal to the source because it’s not initialized yet.