Friday 12 August 2011

Destructors

Destructor

It is a special member function, which contains ~ (tilde) symbol, which is used to deallocate the resource of the object.
Like constructors, we can not call the destructors, it is called automatically just before object is lost.


A destructor as the as the name implies is used to destroy the objects that have been created by a constructor.
1.      Like a constructor, the destructor is a member function whose name is the same as the class name but it is preceeded by a tilde.
Tilde representation is”   ~”
Rules for the Destructors:




1.      Destructor  cannot be overloaded.
2.      Destructor do not require any arguments, not even the return type.
3.      Desturctors  are the only way to destroy objects.
4.      Whenever the program is terminated by either return or exit statements, the destructor is executed.
5.      It does not take parameters.
6.      It is a good practice to declare destructors in a program since it releases memory space for future use.
7.      We use destructor to clean up storage that is no longer accessible.

Example 1:
#include<iostream.h>                                                                                                
class Example
{
     private:
     int data;
     public:
     Example()            //constructor(same name as class)
     {
        cout<<”inside the constructor”;
     }

     ~Example()   //destructor(same name as class name but preceded by tilde symbol)
      {
      cout<<”inside the destructor”;
       }
};

void main()
{
   Example e;
}


Example 2:
#include<iostream.h>
class A
{
public:
~A()
{
Cout<<”I am constructor A;
}
};
class B:public A
{
Public:
~B()
{
cout<<”I am destructor B;
}
};

void main()
{
    B,B1;
}

OUTPUT:
I am constructor A
I am constructor B
I am destructor B
I am destructor A



No comments:

Post a Comment