Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copy Assignment CSCE 121 J. Michael Moore.

Similar presentations


Presentation on theme: "Copy Assignment CSCE 121 J. Michael Moore."— Presentation transcript:

1 Copy Assignment CSCE 121 J. Michael Moore

2 Overload ‘=‘ Operator ‘=‘ is the assignment operator
Allows class to perform expected deep copy behavior

3 Using Copy Assignment MyClass object1, object2; // modify object 1 object2 = object1;

4 Declaration ClassName& operator=(const ClassName& source); a = b; a.operator=(b);

5 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!

6 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.


Download ppt "Copy Assignment CSCE 121 J. Michael Moore."

Similar presentations


Ads by Google