WRITE A PROGRAM FOR DESTRUCTOR IN C++

 Que - what is destructor?

Ans- DESTRUCTOR is a special type of member function of class, which is same name as class and it is use for destroy the memory allotted by the Constructor. To use the destructor we use a tiled sign (~) .

Destructor same as Constructor automatically call on the time of object declaration. 

Some important points about destructor:-

  • It is not possible to define more than one destructor. 
  • The destructor is only one way to destroy the object create by constructor. Hence destructor can-not be overloaded.
  • Destructor neither requires any argument nor returns any value.
  • It is automatically called when object goes out of scope. 
  • Destructor release memory space occupied by the objects created by constructor.
  • In destructor, objects are destroyed in the reverse of an object creation.

Example of destructor:-

#include<iostream>
using namespace std;

class krishna
{
   int radius;
   float area,pi;
   public:
   krishna ()
{
   pi=3.14;
}
void getdata ()
{
  cout<<"enter radius of circle :-";
  cin>>radius ;
  area=pi*radius*radius ;
  cout<<"area of circle is:-"<<area<<endl;
}
~krishna()
{
   cout<<"destructor execute";
}
};
int main()
{
   krishna ob ;
   ob. getdata ();
   return 0;
}

Result:-


Post a Comment

Previous Post Next Post