Vtable placement of completely pure-virtual class
According to my (limited) knowledge of the C++ spec, the vtable of a class with virtual members is placed at开发者_C百科 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?
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.
EDIT from 2020: I wrote this almost a decade ago. I suspect I wrote it from memory and personal experience. Two comments below indicate that compilers do make vtables for base classes (to throw errors), although if so I don't know how you would construct an object for them, and that some compilers do reuse vtables of base classes. Nobody seems to have added anything since 2011, and I have cognitive decline now and it's hard to really think much anymore, so do some research of your own if some detail here is crucial.
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.
精彩评论