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