Question

According to my (limited) knowledge of the C++ spec, the vtable of a class with virtual members is placed at the definition of the first non-pure non-inline virtual method. How do compilers handle classes which inherit from a class with ALL pure virtual methods (interfaces, for example)? Where is the vtable placed in this case?

Was it helpful?

Solution

The vtable stores the addresses of the implemented virtual methods. If all methods of a class are pure-virtual and none are implemented, then no vtable needs to be generated.

You could not use such a class for much without some classes which derive from it and implement the methods. Each class with implemented virtual methods has its own single vtable containing addresses for all virtual methods: it does not in any way reference the vtables of base classes; the addresses are duplicated. So if you have a class which inherits from another class, that class will use just its own vtable. It doesn't care about the vtable of the base class; this vtable doesn't even need to exist.

The C++ specification itself says nothing about vtables; they are simply a compiler behaviour which has become common.

OTHER TIPS

The C++ standard doesn't specify anything about vtable placement, or even the existence of a v-table. It just specifies behavior, and a v-table happens to be the most straightforward implementation, hence widely used.

Practically speaking, the one reason for a v-table to exist for an abstract class is for use during construction and destruction, when the dynamic type of the object is the abstract class.

In a class with only pure virtual functions, there clearly can be no constructors (since constructors cannot be virtual). However, destructors certainly CAN be virtual.

Your class could still have a pure virtual destructor with an implementation and then the v-table (or equivalent implementation details) is required.

But implementations of pure virtual functions are rare, and wouldn't be done when defining an interface.

You don't need a vtable until you have an instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top