How to Call Destructor In C++


A Destructor is a special member function whose name is same as that of its class name except that it is preceded by a tilde (~) symbol. A destructor is used to perform the cleanup process (typically deallocating the dynamically allocated memory). Like a constructor, destructor too has no return type. Only one destructor is possible for a class. So destructors cannot be overloaded. The Compiler calls destructor implicitly just before an object goes out of its scope.

How to Call Destructor In C++ Example

#include<iostream> using namespace std; class Hello1{ public: Hello1(){ cout<<"Constructor is called here"<<endl; } ~ Hello1(){ cout<<"Destructor is called here"<<endl; } }; int main(){ Hello1 h1; return 0; }

Output:-

Constructor is called here
Destructor is called here

Explanation of the program

Constructor gets called as soon as memory is allocated to the object of the class sample. Destructor gets called just before the object h1 dies.