3

Discussion

I'm aware that all the implementations (i.e., C++ compilers) that I know, implement the dynamic dispatch mechanism via the use of virtual dispatch tables and virtual table pointers (i.e., the known vtable and vptr).

However, interrogating the C++ standard I found out that the C++ standard does not mandate exactly how dynamic dispatch must be implemented. This means that a vendor could use an alternative method for dynamic dispatch provided that its behaviour complies to the C++ standard demands for dynamic dispatch behaviour.

Questions

Q1. Are there any other valid methods, beside vtables and vptrs, that dynamic dispatch could be implemented with?

Q2. If Q1 is true: What are the reasons, if any, that made implementers decide to use vtables and vptrs to implement dynamic dispatch instead of some other valid method?

101010
  • 41,839
  • 11
  • 94
  • 168

1 Answers1

2

Q1: Dynamic compilers can implement virtual functions faster than using a vtable. Say a method is virtual, but all objects created so far use implementation X. A dynamic compiler will produce a direct call to implementation X or even inline it. When an object using a different implementation is created, all the code that might now be wrong will be recompiled.

Even if there are two implementations, the dynamic compiler may produce code like "if (object uses implementation X) { inlined_code_for_x (); } else { recompile_this_code (); }

Q2: A potential reason: If you have a base class with many virtual functions and a huge vtable, and many derived classes which rarely override any of these virtual functions, then having the same vtable for each class is inefficient. Both from a memory point of view, and potential from an execution point of view, because certain processor optimisations don't work if pointers to the same function are stored in different memory locations.

gnasher729
  • 51,477
  • 5
  • 75
  • 98