Skip to content
Guest
Learn C++ · Course Syllabus Show lessons
OOP & Resource Safety · 9 min read · Intermediate

Classes, Constructors & RAII

Encapsulate state with C++ classes, member initializer lists, and deterministic RAII resource cleanup.

What you'll learn

  • Initialize class members cleanly with a member initializer list
  • Mark read-only member functions const
  • Understand RAII (Resource Acquisition Is Initialization) and destructors

RAII (Resource Acquisition Is Initialization) is the most important idiom in C++: tie every resource (memory, file handles, mutex locks) to an object’s lifetime. The constructor acquires the resource, and the destructor (~ClassName()) releases it automatically the instant the object leaves scope, even if an exception is thrown.

const Member Functions

Adding const after a method signature (for example, double balance() const) promises the compiler that calling the method will not mutate the object, allowing it to be called on const references.

Fill-in-the-Blank Exercise

Member Initializer & Const Method

Initialize balance_ in the initializer list and mark balance() as const.

class Account {
  double balance_;
public:
  Account(double start)  balance_(start) {}
  double balance()  { return balance_; }
};

Interactive Code Lab

C++raii_class.cpp
Expected OutputClick “Run Live” to compile with GCC 13 (C++20)
[START] Build Step
Running work...
[END]   Build Step

Check Your Understanding

Score: 0 / 1

1. When does a C++ stack object's destructor run under RAII?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind