Rule of Three Part 1 & 2
Rule of Three Any object which manages memory needs: Custom Destructor Custom Copy Constructor Custom Assignment Operator
Destructor Destructor : Special function called when object destroyed Automatically called Almost never called by hand ~CLASSNAME()
Destructors Stack objects destroyed when leave scope:
Destructors Heap objects must be destroyed manually:
Cleaning Up Memory allocated by object = potential leak
Cleaning Up Memory allocated by object = potential leak
Destructor Destructor used to clean up owned resources: New in constructor delete in destructor
Copy Constructor Every class has a default implicit copy constructor Class::Class (const Class &other) Created invisibly and automatically
Copy Constructor Using copy constructor: p2 is copying p1
Copy Constructor Default works for simple objects: p1 p2 x: 4 y: 3
The Issue Default copy constructor for Polygon
The Issue Copies sides
The Issue Copies vertices pointer
The Issue Two objects now share one list of points
Shallow copy Shallow copy : duplicate pointers of an object Copy shares memory with original
Deep copy Deep copy : duplicate memory owned by original Copy gets own version of data
Copy Constructor Deep copy constructor Copy basic variables Allocate own storage Copy data to it
Copy Constructor Deep copy constructor Copy basic variables Allocate own storage Copy data to it
Copy Constructor Deep copy constructor Copy basic variables Allocate own storage Copy data to it
Copy Constructor Deep copy constructor Copy basic variables Allocate own storage Copy data to it
Book Sample
Book Example Course class introduced in Ch 11
Book Example Constructor allocates array Destructor deletes
Book Example Book Ex11.20 copy constructor Has typo – missing last 2 lines in book Should be:
Copy Constructor Deep copy recipe: Copy basic variables Allocate own storage/resources Copy data from other to own storage
Copy Constructor Recipee For Course: