Destructor in c++ is a special member function because it’s name is the same as classname with preceded by a tilde (~) sign.
it do not have any Argument and return type.
it’s called automatically when the object of the class is Destroyed. (means terminate of program or end of the block)
it is used to destroy the object. (Release the Memory used by Object)
The syntax to Define Destructor in c++ is : :
class classname
{
public :
tilde_sign(~)Destructor_na me() // Destructor_name is same as classname
{
.
.
.
}
};
Also read this :- Constructor In C++
Here’s an example of a Default Destructor in c++
#include<iostream>
#include<conio.h>
using namespace std;
int c = 0;
class xyz
{
public :
xyz()
{
c++;
cout<<"n Object is Created = "<<c;
}
~xyz()
{
cout<<"n Object is Destroyed = "<<c;
c--;
}
};
int main()
{
xyz x1, x2, x3;
{
cout<<"n Inner Block 1 ";
xyz x4;
}
{
cout<<"n Inner Block 2 ";
xyz x5;
}
cout<<"n End of Program ";
return 0;
}
output
Object is Created = 1 Object is Created = 2 Object is Created = 3 Inner Block 1 Object is Created = 4 Object is Destroyed = 4 Inner Block 2 Object is Created = 4 Object is Destroyed = 4 End of Program Object is Destroyed = 3 Object is Destroyed = 2 Object is Destroyed = 1