AnyCompiler

Constructors and RAII

A destructor, written as the class name prefixed with ~, runs automatically when an object goes out of scope — deterministically, not at some unpredictable later point the way a garbage collector's finalizer might. This pairing of a constructor that acquires a resource with a destructor that releases it is RAII: Resource Acquisition Is Initialization.

#include <iostream>
using namespace std;

class Logger {
public:
    Logger() {
        cout << "Logger created" << endl;
    }
    ~Logger() {
        cout << "Logger destroyed" << endl;
    }
};

int main() {
    cout << "Before scope" << endl;
    {
        Logger log;
        cout << "Inside scope" << endl;
    }
    cout << "After scope" << endl;
    return 0;
}
Output
Before scope
Logger created
Inside scope
Logger destroyed
After scope

Notice the exact order: the destructor runs the instant log leaves its enclosing block, before 'After scope' even prints. This is the core idea behind every resource-managing type in C++ — file handles, locks, and the smart pointers covered later in this course all lean on exactly this mechanism, rather than a garbage collector's indeterminate timing.

Next: encapsulation — access control, and why making fields private matters once a class has invariants to protect.

Practice exercise

Define a class Counter whose constructor prints "Counter started" and whose destructor prints "Counter finished". Create a Counter in main, print "Running" after creating it, then let it go out of scope.