How do virtual destructors work?

I am using gcc. I know how virtual destructors solve the problem when we destroy the object of the derived class indicated by the base class pointer. I want to know how they work?

class A { public: A(){cout<<"A constructor"<<endl;} ~A(){cout<<"A destructor"<<endl;} }; class B:public A { public: B(){cout<<"B constructor"<<endl;} ~B(){cout<<"B destructor"<<endl;} }; int main() { A * a = new B(); delete a; getch(); return 0; } 

When I change the destructor to a virtual function, the problem is resolved. What is the inner workings for this. Why am I making a destructor virtual. I want to know what happens with vtable A and B?

+4
source share
2 answers

The key thing you need to know is that not using a virtual destructor in the above code is undefined behavior and that is not what you want. Virtual destructors are like any other virtual function - when you call delete , the program will decide which destructor should call right at run time and which solves your problem.

+4
source

A virtual destructor is just a virtual function, so it follows the same rules.

When you call delete a , the destructor is implicitly called. If the destructor is not virtual, you call a->~A() , because it is called like any other non-virtual function.

However, if the destructor is virtual, you call ~B() , as expected: the destructor function is virtual, so the invoked call is the destructor of the derived class, not the base class.

Edit:
Note that the base class destructor will be invoked implicitly after the derived class destructor completes. This is different from ordinary virtual functions.

+6
source

Source: https://habr.com/ru/post/1307664/


All Articles