Why is not the destructor of a virtual class automatically added to the vtable?

When virtual class B derives from a virtual base class A, unless explicitly declaring a virtual destructor in A and B, B's destructor in the vtable will point to A's destructor. Why? Why doesn't the B's vtable destructor point on B's destructor automatically without having to define A and B virtual destructors?

edit: realized that without making A's destructor virtual, B's destructor isn't even in the vtable so when calling A's destructor it justs direct calls A's. My question doesn't make sense.

1 answer

  • answered 2018-04-14 15:52 Sebastian Redl

    C++ works on the principle of "you don't pay for what you don't use". Forcing the destructor of any class that has any virtual function to be virtual, even if the clients of the class never delete objects of that class polymorphically (i.e. through a base pointer), is a non-zero cost (slot in the vtable, deletes on the object needing a virtual function call). Therefore, C++ doesn't do that without explicit instruction.