Search code examples
c++polymorphismvtable

C++ virtual destructor & vtable


I have some specific questions on virtual destructors and vtable.

Suppose I have the following code:

class Base
{
public:

    virtual ~Base();

};

class Child : public Base
{
public:

    ~Child();
};

Questions:

  1. Where is the vtable stored? Is it always in the base class and all sub-classes simply keeps a pointer to it?
  2. Adding a virtual method only increases the sizeof(class) by 8 bytes right? (assume 64bit system) How about base class if it stores the table?
  3. Creating an instance of type Child via the new operator then delete ... will the Base destructor be called? (I'm asking because Child class's destructor isn't virtual ... does that mean it only affects sub-class of Child?).

Solution

  • The explanation below assumes that virtual dispatch implementation used by the compiler is based on virtual tables.

    1. Each class with virtual methods (declared or inherited) has its own virtual table. If a subclass overrides a virtual member function in the base, a pointer to the overriding function is placed in the class's vtable; otherwise, a pointer to base class implementation is kept in place.

    2. Adding the first virtual function increases the size of the class instance by the size of vtable pointer. Virtual functions after the first one do not add to the size of the instance.

    3. Since ~Base is virtual, the ~Child is virtual as well, even though virtual keyword is omitted. In case of an override, virtual keyword is optional.