There are many different ways to implement such dynamic dispatch, but use of virtual method tables is especially common among C++ and related languages (such as D and C#).
[1] Suppose a program contains three classes in an inheritance hierarchy: a superclass, Cat, and two subclasses, HouseCat and Lion.
Class Cat defines a virtual function named speak, so its subclasses may provide an appropriate implementation (e.g. either meow or roar).
[2] The C++ standards do not mandate exactly how dynamic dispatch must be implemented, but compilers generally use minor variations on the same basic model.
[4] Consider the following class declarations in C++ syntax: used to derive the following class: and the following piece of C++ code: g++ 3.4.6 from GCC produces the following 32-bit memory layout for the object b2:[nb 1] and the following memory layout for the object d: Note that those functions not carrying the keyword virtual in their declaration (such as fnonvirtual() and d()) do not generally appear in the virtual method table.
An experiment done in 1996 indicates that approximately 6–13% of execution time is spent simply dispatching to the correct function, though the overhead can be as high as 50%.
[5] The cost of virtual functions may not be so high on modern CPU architectures due to much larger caches and better branch prediction.
In certain cases it may be possible for the compiler to perform a process known as devirtualization in which, for instance, the lookup and indirect call are replaced with a conditional execution of each inlined body, but such optimizations are not common.
Virtual method tables also only work if dispatching is constrained to a known set of methods, so they can be placed in a simple array built at compile time, in contrast to duck typing languages (such as Smalltalk, Python or JavaScript).
Languages that provide either or both of these features often dispatch by looking up a string in a hash table, or some other equivalent method.
There are a variety of techniques to make this faster (e.g., interning/tokenizing method names, caching lookups, just-in-time compilation).