How the virtual mechanism works in the case of a virtual destructor

How to get a pointer to a member function of a destructor?

here someone replied that we cannot get a pointer to the function of the destructor then how the virtual mechanism works in the code below. Is the virtual constructor stored in a virtual table or not? if not, how does the virtual mechanism work in the case of a virtual destructor?

#include<stdio.h> class Base { public: Base() { printf("C-Base\n"); } virtual ~Base() { printf("Base\n"); } }; class Derived:public Base { public: Derived() { printf("C-DErived\n"); } ~Derived() { printf("DErived\n"); } }; int main() { Base *b=new Derived(); delete b; } 

in this code, if we do not use a virtual in the base class Destructor Derived class, the destructor will not be called.

+4
source share
2 answers

When someone says that you cannot get a pointer to a destructor, it means that there is no syntax for this at the source code level. But under the hood, the destructor is still a normal function, which is usually accessed through a pointer stored in a virtual table.

In other words, it is you who cannot get such a pointer. The compiler itself has no problems getting it. License Quod Iovi non licet bovi.

+9
source

Just because you cannot get a pointer to a destructor does not mean that the compiler cannot fulfill its own internal, vile goals.

(As a side note, the compiler often generates more than one version of the destructor with more than one entry in the vtable, which makes it incompatible with regular function pointers.)

+5
source

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


All Articles