Destructors in C++
In this lesson: What destructors do in C++, order of execution and RAII cleanup — examples with output. In Hindi & English.
What is a destructor?
A destructor is the opposite of a constructor: it runs automatically when an object is destroyed, giving it a chance to clean up — free memory, close files, release resources. Its name is the class name with a leading ~, and it takes no arguments.
Syntax and example
#include <iostream>
using namespace std;
class Logger {
public:
Logger() { cout << "Created\n"; } // constructor
~Logger() { cout << "Destroyed\n"; } // destructor
};
int main() {
Logger l; // "Created"
cout << "Working...\n";
return 0; // "Destroyed" runs here
}Created
Working...
Destroyed
When is it called?
- When a local object goes out of scope (its block ends).
- When a heap object is
deleted. - When the program ends, for objects still alive.
Local objects are destroyed in the reverse order they were created.
Freeing resources
The classic use is releasing memory a class allocated with new:
class Buffer {
int *data;
public:
Buffer(int n) { data = new int[n]; } // acquire
~Buffer() { delete[] data; } // release
};Because the destructor runs automatically, the memory is freed even if you forget — as long as the object is destroyed.
RAII and the rule of three
RAII — Resource Acquisition Is Initialization — is the C++ idea of tying a resource's lifetime to an object: acquire in the constructor, release in the destructor. It makes cleanup reliable even when errors happen.
The rule of three: if your class needs a custom destructor, it usually also needs a custom copy constructor and copy assignment operator, since all three deal with managing the resource. Modern C++ often avoids this entirely by using smart pointers.
Common mistakes
- Forgetting the
~, so it looks like a constructor. - Giving a destructor parameters or a return type (it has neither).
- Needing a custom destructor but ignoring the rule of three (double free).
- Manually managing memory when a smart pointer would handle it automatically.
Write a class whose constructor prints "Opening" and destructor prints "Closing". Create two objects in a block and watch the order of construction and destruction. Then create one with new and delete it.
Summary
- A destructor runs automatically when an object is destroyed.
- Named
~ClassName(), with no arguments or return type. - Called at end of scope, on
delete, or at program end (reverse order). - Used to free memory and release resources — the basis of RAII.
- A custom destructor usually means you need the rule of three.
Frequently Asked Questions
What is a destructor in C++?
~Car(), takes no arguments and returns nothing.