0Pricing
C++ Academy · Lesson

Destructors and Cleanup

Release resources automatically.

What a Destructor Does

A destructor runs when an object's lifetime ends. Its job is to release whatever the object owns. It is named ~ClassName.

#include <iostream>

class File {
public:
    ~File() { std::cout << "closing file\n"; }
};

int main() {
    File f;
}   // ~File runs here

Freeing Owned Memory

If a class owns heap memory, its destructor must free it. This is the classic place to call delete.

#include <iostream>

class Buffer {
    int* data;
public:
    Buffer(int n) : data(new int[n]) {}
    ~Buffer() { delete[] data; }   // cleanup
};

int main() { Buffer b(10); }

All lessons in this course

  1. The RAII Principle
  2. Destructors and Cleanup
  3. Rule of Three/Five
  4. Scope Guards
← Back to C++ Academy