Virtual Destructor in C++

• Pointer is of type Base class and object created using ‘new’ operator is of type Derived class. So, at the time of object creation, constructor invocation is from Base class to Derived class. 

• But while deleting pointer Base, compiler cannot tell that Derived class instance is destroyed. Note that ‘delete’ calls the destructor for the class. 

•This problem can be solved by declaring the destructor of the base class as ‘virtual’. In this way, the destructor will be invoked through virtual function table.

Example:

#include<iostream.h>
class Base

{       public: 
      Base()
      {
            cout<<“Base:Constructor”<<endl;
      } 
    ~Base(){
            cout<<“Base:Destructor”<<endl;
      } 
};
class Derived:public Base 

      Derived(){
            cout<<“Derived:Constructor”<<endl;
      } 
      ~Derived(){
           cout<<“Derived:Destructor”<<endl;
      } 
}; 
main()

      Base *base=new Derived; 
      delete base;
}

Output:
Base:Constructor 
Derived:Constructor 
Base:Destructor


After changing Base class destructor as below:
virtual ~Base()

{
    cout<<“Base:Destructor”<<endl;
}

Output: 

Base:Constructor 
Derived:Constructor 
Derived:Destructor 
Base:Destructor 

No comments:

Post a Comment