Static vs. Dynamic Dispatching

Static dispatching and dynamic dispatching are two different mechanisms used in object-oriented programming languages like C++ to determine which method implementation to use when there are multiple implementations available.

C++ uses:

  • Static Dispatching (Non-Virtual Methods)
    • Static dispatching, also known as early binding, occurs when the method to be called is determined at compile-time based on the static type (declared type) of the object or pointer. In C++, non-virtual member functions use static dispatching. The compiler selects the appropriate method implementation based on the static type of the object or pointer.
  • Dynamic Dispatching (Virtual Method)
    • Dynamic dispatching, also known as late binding, occurs when the method to be called is determined at runtime based on the dynamic type (actual type) of the object. In C++, [virtual member functions use dynamic dispatching]. The decision on which method implementation to use is based on the actual type of the object pointed to by the pointer.
    • Allows for polymorphism, where derived classes can provide their own implementation of the virtual method.
    • Dynamic dispatching is achieved in C++ using a virtual function table (vtable) and virtual function pointers. The vtable contains pointers to the virtual functions of a class, and each object of a class with virtual functions contains a hidden pointer (vptr) that points to its vtable. This mechanism enables the selection of the appropriate method implementation based on the dynamic type of the object. By using virtual methods and dynamic dispatching, you can achieve runtime polymorphism, where the appropriate method implementation is selected based on the actual type of the object at runtime, rather than the static type determined at compile-time.