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

Lessons

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

Module quiz

1. Who can use a private data member?
2. When does a constructor run?
3. What must memory from new int[10] be released with?
4. Objects a, b and c are created in that order in one block. Which is destroyed first?
5. A class has an int* member and no copy constructor. What happens after Buffer b = a;?
6. Which member function runs for c = a; when c already exists?
7. Why does a copy assignment operator check this != &other?

‹ From C to C++Static members and operators ›