Skip to main content
Module 4 · Lesson 2 of 210/26 in the course~14 min
Module lessons (2/2)

Builders and Destroyers

Lesson preview5 hands-on exercises readyCourse C++ · Module 4 — Object Oriented Programming

Initialize object state upon creation and cleanup resources upon destruction.

What you'll learn in this lesson

  • Correctly initialize each member at birth via the member initializer list (: field(val)).
  • Understand when the compiler suppresses the default constructor and how to restore it with = default.
  • Use destructors (~Class()) as the foundation of RAII to release resources in deterministic order.

Overview

In C++ an object should never exist in a semi-initialized state. Constructors and destructors are automatic hooks invoked by the compiler exactly when creating and leaving the scope of the object.

A constructor has the same name as the class and has no return type. The best form in C++ to value members is the member initializer list (after the colon : before the body {}):

Sections covered in this lesson

  1. 11. Builders and Member Initializer List
  2. 22. Default Constructor and = default / explicit
  3. 33. Destructor ~Class() and LIFO Order
  4. 44. The RAII Idiom (Resource Acquisition Is Initialization)
  5. 5Practical exercises
  6. 6Check for understanding
Pro Lesson · Module 4 — Object Oriented Programming

Unlock "Builders and Destroyers" and the full Course C++ curriculum

Initialize object state upon creation and cleanup resources upon destruction.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course C++ plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.