Importance of a Virtual Destructor

To understand the importance of Virtual Destructor, let us consider the below program:

#include<iostream>
using namespace std;

class Base{
    private:
        char *b;
    public:
        Base()
        {
            b=new char[5];
        }
        ~Base()
        {
            cout<<"Base Destructor \n";
        }
};

class Derived{
    private:
        char *d;
    public:
        Derived()
        {
            d=new char[5];
        }
        ~Derived()
        {
            cout<<"Derived Destructor \n";
        }
};

int main()
{
    Base *array[2]={new Base, new Derived};
    delete array[0];
    delete array[1];

    return 0;
}
Solution:
Base Destructor
Base Destructor

Explanation:
delete array[0] calls Base::~Base() and delete array[1] also calls Base::~Base() , this is because array[0] and array[1] are of Base class type. But we expected array[1] to call Derived::~Derived().
To do this the above program is slightly modifed as below.

#include<iostream>
using namespace std;

class Base{
    private:
        char *b;
    public:
        Base()
        {
            b=new char[5];
        }
        virtual ~Base()
        {
            cout<<"Base Destructor \n";
        }
};

class Derived:public Base{
    private:
        char *d;
    public:
        Derived()
        {
            d=new char[5];
        }
        ~Derived()
        {
            cout<<"Derived Destructor \n";
        }
};

int main()
{
    Base *array[2]={new Base, new Derived};
    delete array[0];
    delete array[1];

    return 0;
}
Solution:
Base Destructor
Derived Destructor
Base Destructor

1 comments:

Anonymous said...

Can you please list some importance of virtual destructor?

Post a Comment