Destructors in C++: Memory Cleanup & Order of Invocation
1. What is a Destructor? (In Simple Words)
When you create an object, the Constructor sets up variables and allocates memory.
When the object’s work is finished (for example, when a function ends or a block {} closes), that memory must be cleaned up and returned to the system so RAM is not wasted.
A Destructor is a special member function that is called automatically by the compiler when an object is destroyed. Its main job is to clean up resources — like deleting dynamically allocated memory (delete), closing opened files, or disconnecting from databases.
Student s1;Constructor: Allocates memory & initializes variables.
} reachedDestructor: Frees memory & cleans up resources!
Real-Life Analogy: When you leave a hotel room or a college classroom at the end of the day, you turn off the AC, switch off lights, and lock the door so electricity isn’t wasted. A destructor does the exact same cleanup in computer memory!
2. Key Characteristics of Destructors (Golden Exam Points)
- Tilde Symbol (
~): It has the exact same name as the class, but starts with a tilde symbol (~) (e.g.~Student()). - Takes No Arguments: A destructor never takes any parameters.
- Cannot be Overloaded: Because it takes no arguments, a class can have ONLY ONE destructor!
- No Return Type: Just like constructors, it has no return type, not even
void. - Called Automatically: The compiler calls it automatically when an object reaches the end of its block
{}. - Can be Virtual: Unlike constructors (which cannot be virtual), Destructors CAN be declared
virtual(important when working with inheritance).
3. Order of Constructor and Destructor Execution (LIFO Rule)
⚠️ GOLDEN EXAM RULE:
In C++, constructors run in normal order (first created, first initialized).
Destructors ALWAYS run in the EXACT REVERSE order: Last In, First Out (LIFO)!
The object created last is destroyed first (just like plates stacked in a wedding buffet: the top plate placed last is picked up first!).
#include <iostream>
using namespace std;
int count = 0; // Global counter
class Tracker {
private:
int id;
public:
// Constructor
Tracker() {
count++;
id = count;
cout << "Constructor called for Object #" << id << endl;
}
// Destructor (Notice the '~' symbol)
~Tracker() {
cout << "Destructor called for Object #" << id << endl;
count--;
}
};
int main() {
cout << "Inside main(): Creating Object 1" << endl;
Tracker t1;
{
cout << "\n--- Entering Inner Block ---" << endl;
Tracker t2;
Tracker t3;
cout << "--- Leaving Inner Block ---" << endl;
} // t2 and t3 die here at the closing brace!
cout << "\nBack in main(): Program ending..." << endl;
return 0; // t1 dies here!
}
Output Trace (Notice the Reverse Order!):
Inside main(): Creating Object 1
Constructor called for Object #1
--- Entering Inner Block ---
Constructor called for Object #2
Constructor called for Object #3
--- Leaving Inner Block ---
Destructor called for Object #3 <-- Destroyed first (LIFO)!
Destructor called for Object #2
Back in main(): Program ending...
Destructor called for Object #1 <-- First created is destroyed last!
4. Comparison: Constructors vs. Destructors
| Feature | Constructor | Destructor |
|---|---|---|
| Name | ClassName() |
~ClassName() (Preceded by tilde ~) |
| When does it run? | When an object is created | When an object goes out of scope / is deleted |
| Main Job | Allocates memory & initializes variables | Frees heap memory & cleans up resources |
| Overloading | Yes! Can have multiple constructors | No! Only 1 destructor allowed per class |
| Arguments | Can accept 0, 1, or multiple parameters | Never accepts any arguments |
| Can it be Virtual? | No | Yes |
DAVV Exam Preparation Tips
Frequently Asked 5-Mark Questions:
- What is a destructor in C++? State any four of its characteristics.
Model Answer:- Define: A member function that cleans up resources automatically when an object is destroyed.
- 4 characteristics: Same name as class with
~, no arguments, cannot be overloaded, called in reverse (LIFO) order.
- In what order are constructors and destructors executed? Illustrate with a brief example.
Model Answer:- Explain LIFO (Last In, First Out).
- Write a short 10-line code snippet showing objects created as 1, 2, 3 and destroyed as 3, 2, 1.
Frequently Asked 10-Mark Questions:
- Explain the purpose of Constructors and Destructors in Object-Oriented Programming. Differentiate between them in detail. Write a C++ program with dynamic memory allocation demonstrating how destructors prevent memory leaks.
Model Answer:- Explain object lifecycle and resource management.
- Present the 6-point comparison table between Constructor and Destructor.
- Write a class allocating dynamic memory (
int *arr = new int[100];). - Show how the destructor executes
delete[] arr;to release RAM. - Explain Memory Leak: if you don’t release heap memory with a destructor, that RAM stays occupied until the computer restarts.