In this chapter, we will learn about destructor, need for destructor, its characteristics, and destructor examples
What is a Destructor
A Destructor is a special member function of a class that is automatically called when an object is destroyed. Its main purpose is to release resources, free memory, and perform cleanup operations before the object is removed from memory.
Just as a constructor initializes an object, a destructor destroys it.
Definition
A destructor is a special member function that is automatically executed when an object goes out of scope or is deleted.
Example of Destructor in real life
Imagine you rent a hotel room.
Constructor: Checks you into the room and prepares everything.
Destructor: Cleans the room after you leave.
Similarly,
Constructor allocates resources.
Destructor releases resources.
When is a destructor called?
A destructor is called automatically in the following situations:
When an object goes out of scope
When the program ends
When a dynamic object is deleted
Characteristics of Destructor
A destructor has the following characteristics:
It has the same name as the class.
It is preceded by the tilde (~) symbol.
It does not take any arguments.
It does not return any value, not even void.
Only one destructor can exist in a class.
It is called automatically.
It cannot be overloaded
Syntax of a Destructor
~ClassName()
{
// Statements
}
Example
~Employee()
{
cout << “Destructor Called”;
}
Example - Destructor Program
#include<iostream>
using namespace std;
class Demo
{
public:
Demo()
{
cout<<“Constructor Called”<<endl;
}
~Demo()
{
cout<<“Destructor Called”<<endl;
}
};
int main()
{
Demo obj;
return 0;
}
Output
Constructor Called
Destructor Called
Explanation
Object obj is created.
Constructor executes automatically.
When main() ends, the object is destroyed.
Destructor executes automatically.
Important Board Examination Points
Destructors have same name as class name preceded by ~.