When we will delete an object of the derived class using a pointer to the base class that has a non-virtual destructor a results in undefined behavior.
So virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to the base class. Let see an example code,
#include<iostream>
using namespace std;
class base
{
public:
base()
{
cout<<"Constructing base \n";
}
virtual ~base()
{
cout<<"Destructing base \n";
}
};
class derived: public base
{
public:
derived()
{
cout<<"Constructing derived \n";
}
~derived()
{
cout<<"Destructing derived \n";
}
};
int main()
{
derived *d = new derived();
base *b = d;
delete b;
return 0;
}
Answer:
When we will delete an object of the derived class using a pointer to the base class that has a non-virtual destructor a results in undefined behavior.
So virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to the base class. Let see an example code,
Output: