Destructor in C++


Destructor is a member function of the class.
It is called special member function because the name of the destructor is same as name of the class but it is preceded by the tilde (~) sign.
Destructor is used to destroy the object that is created using constructor.
Like other member function there is no need to call destructor explicitly. It is invoked automatically each time the object of its class is destroyed. It is invoked when the control of the program exist from the scope in which the object is created.
A destructor does not accept any argument and it does not return any value.
Destructor can be defined inside class as shown below:

     

Class Rectangle
{
int Height, Width;
public:
Rectangle ()
{
Height = 1;
Width = 1;
cout << "Object Created";
}
~Rectangle ()
{
cout << "Object Destroyed";
}
}

Destructor can be defined outside class as shown below:

Class Rectangle
{
int Height, Width;
public:
Rectangle ();
~Rectangle ();
}
Rectangle :: Rectangle ()
{
Height = 1;
Width = 1;
cout << "Object Created";
}
Rectangle :: ~Rectangle ()
{
cout<<"Object Destroyed";
}

Download Projects


Download Programs