A destructor is a special function that cleans up when an object is no longer needed. It helps free resources like memory or files automatically.
0
0
Destructor role in C++
Introduction
When you want to close a file automatically after using it.
When you allocate memory during an object's life and want to free it safely.
When you want to release a network connection when an object is destroyed.
When you want to print a message or log when an object is removed.
When you want to avoid memory leaks by cleaning up resources.
Syntax
C++
class ClassName { public: ~ClassName() { // cleanup code here } };
The destructor has the same name as the class but starts with a tilde (~).
It has no return type and no parameters.
Examples
Basic destructor syntax inside a class.
C++
class MyClass { public: ~MyClass() { // called automatically when object is destroyed } };
Destructor closes a file automatically.
C++
#include <fstream> class FileHandler { public: ~FileHandler() { file.close(); // close file when object is destroyed } private: std::fstream file; };
Destructor frees memory allocated in constructor.
C++
class Buffer { public: Buffer() { data = new int[10]; } ~Buffer() { delete[] data; } private: int* data; };
Sample Program
This program shows when the destructor runs. The object d is created inside a block and destroyed when the block ends.
C++
#include <iostream> class Demo { public: Demo() { std::cout << "Object created\n"; } ~Demo() { std::cout << "Destructor called: Object destroyed\n"; } }; int main() { { Demo d; std::cout << "Inside block\n"; } // d goes out of scope here std::cout << "Outside block\n"; return 0; }
OutputSuccess
Important Notes
Destructor runs automatically when an object goes out of scope or is deleted.
You cannot call a destructor directly; it is called by the system.
If you don't define a destructor, the compiler creates a default one that does nothing.
Summary
Destructor cleans up resources when an object is destroyed.
It has the same name as the class with a ~ prefix and no parameters.
Destructor runs automatically when an object goes out of scope or is deleted.