Dynamic dispatch

In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time.

It is commonly employed in, and considered a prime characteristic of, object-oriented programming (OOP) languages and systems.

[1] Object-oriented systems model a problem as a set of interacting objects that enact operations referred to by name.

Polymorphism is the phenomenon wherein somewhat interchangeable objects each expose an operation of the same name but possibly differing in behavior.

The former is called single dispatch and is directly supported by common object-oriented languages such as Smalltalk, C++, Java, C#, Objective-C, Swift, JavaScript, and Python.

In these and similar languages, one may call a method for division with syntax that resembles where the parameters are optional.

This is thought of as sending a message named divide with parameter divisor to dividend.

By contrast, some languages dispatch methods or functions based on the combination of operands; in the division case, the types of the dividend and divisor together determine which divide operation will be performed.

Examples of languages that support multiple dispatch are Common Lisp, Dylan, and Julia.

C++ compilers typically implement dynamic dispatch with a data structure called a virtual function table (vtable) that defines the name-to-implementation mapping for a given class as a set of member function pointers.

Each compiled library needn't know the full range of interfaces supported in order to correctly use a type, just the specific vtable layout that they require.

Real Smalltalk implementations often use a technique known as inline caching[5] that makes method dispatch very fast.

The common case will be a cached class match, and execution will just continue in the method.

Many other dynamically typed languages, including Python, Ruby, Objective-C and Groovy use similar approaches.