Destructor
·
The member functions which delete the values of the
variables after the ending the working of an object are called destructor.
·
A destructor is a member function having sane name
as that of its class preceded by ~(tilde) sign and which is used to destroy the
objects that have been created by a constructor. It gets invoked when an
object’s scope is over.
~Circle() {}
Example :
·
In the following program constructors,
destructor and other member functions are defined inside class definitions.
·
Since we are using multiple constructor in class
so this example also illustrates the concept of constructor overloading.
#include<iostream.h>
class circle //specify a class
{
private :
double radius; //class data members
public:
circle() //default constructor
{
radius = 0;
}
circle(double r) //parameterized constructor
{
radius = r;
}
circle(circle &t) //copy constructor
{
radius = t.radius;
}
void setRadius(double r) //function to set data
{
radius = r;
}
double getArea()
{
return 3.14 * radius * radius;
}
~circle() //destructor
{}
};
int main()
{
Circle c1; //defalut constructor invoked
Circle c2(2.5); //parmeterized constructor invoked
Circle c3(c2); //copy constructor invoked
cout << c1.getArea()<<endl;
cout << c2.getArea()<<endl;
cout << c3.getArea()<<endl;
return 0;
}
Advantages
of Destructor
·
Destructors
have the opposite function of a constructor. The main use of destructors is to
release dynamic allocated memory.
·
Destructors
are used to free memory, release resources and to perform other clean up.
·
Destructors
are automatically named when an object is destroyed.
·
Like
constructors, destructors also take the same name as that of the class name.