DESTRUCTORS
It is also a memeber function of the class with same name as class but is preceded by title('~').
Syntax: ~destructor-name()
{ body }
NOTE: No matter how many constructors are there in a program, there will be only one destructor needed to destroy all the objects.
Why do we need Destructors?
During the construction of an object, resources may be allocated, that means memory is allocated to an object. Now before destroying an object we need to deallocate them. So destructor is used for clean-up tasks.Example:
class Sample{
int a;
int b;
~Sample(){cout<<"Destructing";} //Destructor
public:
Sample(){a=0; b=0;}
void fun1();
void fun2();
};
Now if the objects of class "Sample" are created in order then their objects are destroyed in reverse order. This is done by Destructor.
For Example:
{Sample s1; //Object s1 created
Sample s2; //Object s2 created
//Object s2 destructed
//Object s1 destructed
}
The objects s1 and s2 were destroyed by the destructor "~Sample()".