views:

142

answers:

4

Hello,

  1. How can i control the order of virtual functions in the virtual table? Are they laid out in the same order that they are declared in?

  2. When inheriting a class with a virtual table, is the virtual table of the inherited class an extension of the base class, or is an entirely new virtual table created with only the inherited classes virtual functions. (i.e. is the virtual table still at index +0x0 of the class?)

+7  A: 

That's completely implementation defined. The C++ standard does not specify any sort of a virtual function table at all -- that's just how it's typically implemented.

Billy ONeal
+2  A: 

Virtual table is implementation specific. It may be laid out in any order. Even there may be no virtual table at all to implement polymorphism. I recommend this article on Wikipedia, which gives some answers to your questions.

doc
+4  A: 
  1. (a) As far as the standard is concerned, you can't, (in fact you can't even assume that vtables exist). (b) Probably, but what are the circumstances in which you need to control the order, but you can't check for yourself? The way to check is to look at the disassembly of a virtual call (and find the offset(s) added to the vtable pointer to get the call address) or to look at the disassembly of the vtable itself.

  2. Depends. For single inheritance, probably it's an extension of the base class, and index 0 of each object points to a virtual table for the class, with pointer to the correct implementation (perhaps an override) for each virtual function declared in base classes, followed by pointers to each virtual function declared in the derived class. For multiple and virtual inheritance it isn't (can't be) that simple. Each object will contain several pointers, either to vtables or to structures which contain vtables plus other class information, and when you cast around the class hierarchy, the pointer value of the object changes. Try it and see.

All of this for a very hypothetical, "typical implementation". Compiler-writers have their tricks.

Steve Jessop
A: 

The question your question really begs is for what reason would you ever need to have the vtable in a particular order?

One of the reasons this is implementation dependent is because a compiler may make choices about how to layout the vtable for performance reasons, or other requirements, particular to a given CPU architecture.

watsond