Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How virtual mechanism works in the case of virtual destructor

How do I get the member function pointer of a destructor?

here some-one answered that we can't get the function pointer of a destructor then how the virtual mechanism work in the below code. Is virtual constructor is saved in the virtual table or not?? if not then how virtual mechanism work in the case of 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 not use virtual in Base class Destructor Derived class destructor will not called.

like image 468
Kushagra Jaiswal Avatar asked Dec 06 '22 07:12

Kushagra Jaiswal


1 Answers

When someone says that you can't get a pointer to the destructor it means that there is no source-code-level syntax for this. But under the hood the destructor is still an ordinary function, which is indeed typically accessed through a pointer stored in the virtual table.

In other words, it is specifically you, who can't obtain such a pointer. The compiler itself has no problems obtaining it. Quod licet Iovi non licet bovi.

like image 188
AnT Avatar answered Mar 03 '23 22:03

AnT