ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

C++ Tutorial• 7 min read

Classes, Destructors & RAII

Resource Acquisition Is Initialization: The core architectural pattern of C++

RAII (Resource Acquisition Is Initialization) is the foundational design pattern of C++: resources (memory, file handles, mutex locks) are acquired in constructors and deterministically released in destructors.

Deterministic Destructors (`~ClassName()`)

Unlike garbage-collected languages (Java, C#) where object cleanup is unpredictable, C++ executes destructors deterministically the exact microsecond an object leaves scope.

Destructor: Prefixed with a tilde: ~DatabaseConnection(). Automatically closes files or frees memory upon function return or exception unwinding.

RAII File Wrapper Class in C++
#include <iostream>
#include <fstream>

class FileLogger {
private:
    std::ofstream file;
public:
    FileLogger(const std::string &filename) {
        file.open(filename); // Resource acquired in constructor
        std::cout << "File opened." << std::endl;
    }

    ~FileLogger() {
        if (file.is_open()) {
            file.close(); // Resource automatically released in destructor!
        }
        std::cout << "File deterministically closed upon scope exit." << std::endl;
    }

    void log(const std::string &msg) { file << msg << std::endl; }
};

int main() {
    {
        FileLogger logger("log.txt");
        logger.log("Logging critical event.");
    } // logger leaves scope HERE: Destructor runs automatically!
    return 0;
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

When is a C++ destructor (`~ClassName()`) executed for a stack-allocated object?