Destructors, static & RAII in C++

From the C++ cheat sheet · Classes & Objects · verified Jul 2026

Destructors, static & RAII

Deterministic cleanup and class-level members.

cpp
// Quick Reference
class File {
public:
    File(const char* p) { f = fopen(p, "r"); } // acquire
    ~File() { if (f) fclose(f); }               // release
private:
    FILE* f = nullptr;
};
💡 RAII: acquire a resource in the constructor, release it in the destructor - cleanup is automatic.
⚡ Destructors run deterministically when an object leaves scope (LIFO order).
📌 static members belong to the class, not any instance, and need one out-of-class definition.
🟢 Smart pointers and containers are RAII types - lean on them instead of new/delete.
destructorsstaticraii

More C++ tasks

Back to the full C++ cheat sheet