i've been learning about virtual methods, and i can grasp the concept pretty easily. But i don't understand the use of virtual destructors,i tried creating a project and experimenting, but i turned out empty handed. My book doesn't seem to explain virtual destructors in depth either . Could anyone help me out on the purpose and use of virtual destructors? Thanks!
#include <iostream>
struct A
{
virtual ~A() { std::cout << "A::~A()\n"; }
};
struct B : A { ~B() { std::cout << "B::~B()\n"; };
int main()
{
{
A *pa = new B;
delete pa;
}
return 0;
}
When the delete is called then it calls in turn the destructor of class A, because the static type of the pointer is A. If there would not be virtual destructor when the destructor for A would be called and the part of the object that belongs to class B would not be destroyed. However when the destructor is virtual the address of the destructor which is in the virtual table is called. This address is the address of the destructor of B. So the destructor for class B is called and after it the destructor of the base class A also is called. In this case the object of type B will be deleted correctly.
That to understand try the same example only remove the reyword virtual for the destructor of A and you will see the difference.