Classes and object lifetime
Writing classes that guard their data, and controlling the whole life of an object: how it is built, where it lives, how it is copied and how it is destroyed.
About 12 hours of study
Learning objectives
- Write classes with private data and public member functions
- Write constructors with initializer lists, and destructors
- Create and delete objects on the heap
- Make deep copies with the rule of three
Lessons
- 1
Classes and objects
A class bundles data with the functions that use it; private members keep the data safe behind public member functions.
- 2
Constructors and destructors
Constructors build an object the moment it is created, destructors clean up when it dies, and objects die in reverse order.
- 3
Objects on the heap: new and delete
new builds an object on the heap and runs its constructor; delete runs the destructor and frees it; new[] needs delete[].
- 4
Copying objects: shallow and deep copies
Copying an object that owns memory copies the pointer, not the memory; the copy constructor, assignment and the rule of three fix it.
Module practice
- C++: A Rectangle classEasy
- C++: A bank account classMedium
- C++: A 24-hour clock classHard
- C++: Two ways to build a pointEasy
- C++: Constructor and destructor orderMedium
- C++: Members are built firstHard
- C++: An array made with newEasy
- C++: An array that grows by doublingMedium
- C++: A linked stack that cleans up after itselfHard
- C++: Copies that look after themselvesEasy
- C++: Repair the assignmentMedium
- C++: A deep copy constructorHard