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
[START] Build Step Running work... [END] Build Step
Check Your Understanding
1. When does a C++ stack object's destructor run under RAII?
Finished this lesson?
Your progress is saved locally in your browser, no account needed.