Dynamic dispatch
From open-encyclopedia.com - the free encyclopedia.
In computer science, dynamic dispatch is the process of mapping a method call to a specific sequence of code at runtime (i.e. dynamically), often in cases where the appropriate method cannot be determined at compile-time (i.e. statically). It is used in object-oriented programming to allow polymorphism.
Dynamic dispatch is performed when multiple classes contain different implementations of the same method foo(). If the type of an object x is not known at compile-time, then when x.foo() is called, the program must decide at runtime which implementation of foo() to invoke, based on the runtime type of object x. This case is known as single dispatch because an implementation is chosen based on a single type--that of the this or self object. Single dispatch is supported by many object-oriented languages, including strongly-typed languages such as C++ and Java, and weakly-typed languages such as Smalltalk and Objective-C.
In a small number of languages such as Common Lisp, methods or functions can also be dynamically dispatched based on the type of arguments. Expressed in pseudocode, the code manager.handle(y) could call different implementations depending on the type of object y. This is known as multiple dispatch.
C++ Implementation
Dynamic dispatch incurs some computational overhead at runtime: when a method is called, a virtual function table or dictionary of methods must be referenced to find the memory address of the appropriate implementation. For this reason, Bjarne Stroustrup, the designer of C++, elected to make dynamic dispatch optional and non-default. Only functions declared with the virtual keyword will be dispatched based on the runtime type of the object; other functions will be dispatched based on the object's static type.
See also
- Dynamic dispatch can be considered a special case of dynamic binding.