C++ Vtable – Order of Function Pointers Explained

ccomvirtual-functions

In this answer to "In C++ why and how are virtual functions slower?",
the author mentions below point:

"Get the right function address from the vtable into a register (the index where the correct function address is stored is decided at compile-time)."

As a follow up of this comment, i have some questions:

  1. What is the order of function pointers stored inside the vtable? Is it compiler dependent or all compilers have to implement it the same way?

  2. If compilers are free to implement it in their own way, then how does binary standard's like COM works. COM relies on the assumption that vtables are implemented in a uniform way by compilers, in order to pass IUnknown pointers to a component compiled by a different compiler. Isn't it?

Best Answer

While it is implementation dependent, it is also fairly predictable.  Especially historically speaking, the compilers layout members in declaration order.  For fields (instance data) that means each field get assigned the next offset in the object (after alignment is rounded up as required), and, each virtual method that is introduced, is assigned next vtable slot.  (Overrides share the same vtable slot as the virtual method that they override in the base class.)

Multiple inheritance complicates field & vtable layouts, introducing a notion of sections that group the field and vtable entries, and, the generated code has to switch between sections as their usage demands.

Because among other things, C is the default standard for foreign function calling, many tools and programs rely on C to layout structs in the predictable order they have always done.

C++ compilers are allowed some latitude for certain constructs these days, but as you have described, to be used with COM (which is of course a Microsoft standard, not a C++ language standard), they have also need to be predictable.

See also:

https://stackoverflow.com/questions/9115020/order-of-fields-in-c-c-structs

https://stackoverflow.com/questions/4178175/what-are-aggregates-and-pods-and-how-why-are-they-special