Is the order of the virtual table important?

There is no notion of vtables in the C++ standard. It's just that most implementations (if not all) use it for virtual dispatch. The exact conventions, however, are totally implementation-defined.

That said... The order of the functions is important, but not for the programmer, but for the compiler - you can arrange your functions however you want in your code. The compiler, however, will typically put each function pointer into a specific place in the vtable, which it has dedicated to that function. So that when it needs to call f() it knows the index of the f() function and takes that pointer from the vtable.

This question might help you as well: Virtual dispatch implementation details


The order of the vtable is important for things to work properly, but only to the compiler (i.e. you don't need to care because it takes care of it).

If the compiler put it out of order for itself, then yeah, things would break, because functions are looked up by offset (so an offset would yield a random function which would be catastrophic).But the average programmer doesn't need to worry about what order the vtable is in.

Tags:

C++