Download presentation
Presentation is loading. Please wait.
1
Rule Of Three Part 3
2
Rule of Three Any object which manages memory needs: Custom Destructor
Custom Copy Constructor Custom Assignment Operator
3
Rule of Three Any object which manages memory needs: Custom Destructor
Custom Copy Constructor Custom Assignment Operator
4
Using Copy Ctor Explicitly
Explicit copy constructor call:
5
Using Copy Ctor Implicitly
Initialization while declaring uses copy constructor:
6
Using Assignment Operator
Assign existing object uses assignment operator
7
Default Assignment Operator
Every class also default assignment operator Copies each member directly: Shallow copy!!!
8
Custom Assignment Operator
Custom assignment operator similar to copy constructor Copy over basic information Allocate own dynamic memory Copy values that are in dynamic memory BUT… Usually returns a reference to the object Already have an object… which already owns memory
9
Custom Assignment Operator
Course assignment operator: I will return a reference to the course that we are copying into I take a reference to a course we will not change Interpreted as course2.=(course1)
10
Why return reference Chained assignments are allowed in C++
Only makes sense if y = 2 resolves to y when done
11
Why return reference Chained assignments are allowed in C++ y
Only makes sense if y = 2 resolves to y when done y
12
Assignment First Pass…
On assignment: Two existing objects Want to turn one into deep copy of other course2 = course1 course2.=(other) course2 is this course1 is other
13
Flawed first attempt… Copy basic stuff
14
Flawed first attempt… Delete old storage
15
Flawed first attempt… Allocate new storage
16
Flawed first attempt… Copy data
17
Flawed first attempt… Return the object that was copied into
18
Self Assignment Danger
Flaw : self assignment deletes data
19
Bad Self Assignment Deleting wipes out storage!!!
20
Bad Self Assignment Allocate a new empty array
21
Bad Self Assignment Loop either copies empty data or blows up array up
22
Final Version Avoid modifying on self assignment:
If address of other is same as this (my address), don't copy
23
Assignment Operator Recipe
Assignment Process Step Pseudocode Verify not self assigning Copy basics Delete old memory Make new array Copy array No matter what, return self if( this != &other) { this.size = other.size … delete [] array array = new whatever[other.size] for(i = 0 to other.size -1) array[i] = other.array[i] } return *this
24
Book Bug Assignment Operator covered in 14.13, but has typos
Does not copy data to new array Missing self assignment check
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.