Stav Alfi
Stav Alfi

Reputation: 13953

Are inherited destructors contained inside the virtual table?

In case my compiler is using virtual tables, how will the virtual table of B look like? Will A::~A be inside B's virtual table?

struct A{
    virtual ~A()
    {
        cout<<"A::destructor"<<endl;
    }
};
struct B:public A{
    ~B()
    {
        cout<<"B::destructor"<<endl;
    }
};

Upvotes: 2

Views: 61

Answers (1)

No, it won't have ~A in the virtual table of B. It will have ~B in the entry that corresponds with the destructor. After all, once a destructor is declared virtual, all deriving destructors are virtual.

So a delete expression will call the correct destructor always. The way the base sub-object A of B is destroyed, can be accomplished simply by the compiler statically injecting a call to ~A at the end of ~B. Conceptually like this:

~B()
{
    cout<<"B::destructor"<<endl;

    //User defined code ended. Compiler generated one is here
    static_cast<A*>(this)->A::~A();
}

This is all delving deeply into possible implementation details. None of this is covered by the C++ standard itself.

Upvotes: 3

Related Questions