website logo

What is Destructors in c++

Destructors is a special member function that mainly used to destroy the object of its class. name of Destructors are same as class name only special character ~ added at the beginning of destructors. destructors never accept any argument like constructor. destructors also not return any value.
compiler call destructors for destroying object upon exit from the program or block or function for cleanup memory .

We write destructors like:

employee :: ~employee()
{

//object deletion code goes hear

}


Example of Destructors in c++


creating and destroying employee object
#include<iostream>
class employee
{

int empno = 1;
public:
employee()
{
empno++;
cout<<
}
~employee()
{

empno--;

}
}
int main()
{
employee e1,e2,e3;
{

cout<<"\n Execute block1\n";
employee e4;

}

{

cout<<"\n Execute block2\n";
employee e5;

}

cout<<"\n Reenter in main function \n";

return 0;

}