C++ · Intermediate level

Intermediate level · Module 1 of 6 · 15 guided hours

Classes, Constructors and Object Lifetime

Write classes that initialise, copy and clean up correctly: constructors, destructors, const correctness, operator overloading and the rule of zero/three.

Learning objectives

  • Write constructors and destructors and explain object lifetime
  • Apply const correctness and overload common operators
  • Apply the rule of zero and recognise when the rule of three is needed

Topics

  • constructors and destructors
  • scope and lifetime
  • const member functions
  • operator overloading (==, <, <<)
  • copy constructor and assignment
  • rule of zero / three

Lessons

  1. Lesson 1 Constructors, Destructors and Lifetime

    Follow an object from construction to destruction and use destructors to release resources automatically.

    object lifetimedestructor ~T()scopeRAII

  2. Lesson 2 const Correctness and Operator Overloading

    Mark what does not change as const, and give classes natural operators such as ==, < and <<.

    const member functionoperator overloadingoperator<< for streamsdefaulted comparisons (C++20)

  3. Lesson 3 Copying Objects: Rule of Zero and Rule of Three

    Understand what happens when objects are copied and why most classes should not define copy operations or destructors at all.

    copy constructorcopy assignmentshallow vs deep copyrule of zero / three

Practical activity

Write a Money class that stores amounts in whole cents with a currency, supports +, == and << and rejects mixing SSP with USD.

Expected outcomes

  • Classes that behave like built-in types where appropriate
  • Correct, leak-free object lifetimes

Assessment

Practical: complete a class so that a provided test program compiles and passes, including copy and comparison behaviour.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.