why we use Virtual Destructor

A destructor is a member function of a class, which gets called when the object goes out of scope.  So we have to do  all clean ups and final steps of class destruction are to be done in destructor.

If a member function is virtual, then calling the function on an object always invokes the function as implemented by the class which is derived finally. If the method is not virtual, then the implementation corresponding to the compile-time type of the object pointer.

Eg:

Class Base
{
public:
Base(){cout<<”Base constructor”;}
~Base{cout<<”Base destructor”;}
}
 
Class Derived: public Base
{
public:
Derived(){cout<<”Derived constructor”;}
~Derived{cout<<”Derived destructor”;}
}
 
void main()
{
Base *Obj = new Derived();
delete Obj;
}

The output will be

 

Base constructor
Derived constructor
Base destructor

From the output we can see that the derived class destructor is not getting evoked. This is where virtual function comes to our aid. If we make the base class destructor as virtual.

Class Base
{
    Base(){cout<<"Base constructor";}
    virtual ~Base{cout<<"Base destructor";}
}

We will get our desired output as

Base constructor
Derived constructor
Derived destructor
Base destructor
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s