This question already has an answer here:
-
When to use virtual destructors?
16 answers
Why do we need a virtual destructor with dynamic variables when we have inheritance? and what is the order for destructor execution in both the static/dynamic case? won't the destructor of the most derived class always execute first?
Imagine you have this:
class A {
public:
int* x;
}
class B : public A {
public:
int *y;
}
main() {
A *var = new B;
delete var;
}
Please assume some constructors destructors.
In this case when you delete A. If you have virtual destructors then the B destructor will be called first to free y, then A's to free x.
If it's not virtual it will just call A's destructor leaking y.
The issue is that the compiler can't know beforehand which destructor it should call. Imagine you have a if above that constructs A or B depending on some input and assings it to var.
By making it virtual you make the compiler deffer the actual call until runtime. At runtime it will know which is the right destructor based on the vtable.
You need a virtual
destructor in the base class when you attempt to delete
a derived-class object through a base-class pointer.
Case in pont:
class Foo
{
public:
virtual ~Foo(){};
};
class Bar : public Foo
{
public:
~Bar() { std::cout << "Bye-Bye, Bar"; }
};
int main()
{
Foo* f = new Bar;
delete f;
}
Without the virtual
destructor in the base class, Bar
's destructor would not be called here.