Topic 51 of 83
Destructors
Overview
Destructors (`~ClassName`) are called automatically when an object goes out of scope or is deleted. They are essential for cleaning up resources like dynamic memory, closing files, or releasing locks (RAII).
Syntax
cpp
class FileHandler {
int* data;
public:
FileHandler() {
data = new int[100]; // Allocate memory
}
// Destructor (starts with ~)
~FileHandler() {
delete[] data; // Free memory!
cout << "Resources cleaned up.";
}
};Common Pitfalls
- Failing to write a destructor when your class allocates memory using `new`, resulting in severe memory leaks.
Interview Tips
- Destructors take no arguments and return no type.
- Explain RAII (Resource Acquisition Is Initialization). In C++, tying resource cleanup to object destructors guarantees that memory/files are freed even if an exception occurs.
Real-World Example
Automated cleanup when object dies.
example
cpp
#include <iostream>
using namespace std;
class Session {
public:
Session() { cout << "Session Started\n"; }
~Session() { cout << "Session Ended (Cleanup)\n"; }
};
void runGame() {
Session s; // Created here
cout << "Playing...\n";
} // s goes out of scope here, Destructor runs!
int main() {
runGame();
return 0;
}