Programming Search⌘K

Conceptcore

Dynamic dispatch

Also called virtual method call, virtual function, late binding, method overriding, vtable, virtual method table, single dispatch, multiple dispatch.

Dynamic dispatch chooses the code for a call at run time from the type of a value, usually the receiver, which lets one call site run the overriding method of each subclass.

Applies to
core-languages

Idea

Dynamic dispatch chooses the code for a call at run time, from the type of a value, usually the object that receives the call. One call site such as s.area() runs the area method of a circle for one object and of a square for the next, and the code at the call site does not know which. Static dispatch makes the choice at compile time instead, from the types that the compiler sees. Dynamic dispatch is the mechanism behind virtual methods, interfaces, trait objects and overriding in object-oriented languages.

def make_class(name, base=None, **methods):  # a class: a name, a base and a method table
    return {"name": name, "base": base, "methods": methods}


def send(obj, selector, *args):  # dynamic dispatch: find the code at run time
    cls = obj["class"]
    while cls is not None:
        if selector in cls["methods"]:
            return cls["methods"][selector](obj, *args)
        cls = cls["base"]
    raise AttributeError(f"{obj['class']['name']} does not understand {selector}")


Shape = make_class(
    "Shape",
    kind=lambda self: "shape",
    describe=lambda self: f"{send(self, 'kind')} with area {send(self, 'area'):.2f}",
)
Circle = make_class("Circle", Shape,
                    kind=lambda self: "circle",
                    area=lambda self: 3.14159 * self["r"] ** 2)
Square = make_class("Square", Shape, area=lambda self: self["side"] ** 2)

shapes = [{"class": Circle, "r": 1.0}, {"class": Square, "side": 2}]
for s in shapes:
    print(send(s, "describe"))  # one call site, two different area methods

try:
    send(shapes[1], "perimeter")
except AttributeError as e:
    print(e)
Output
circle with area 3.14
shape with area 4.00
Square does not understand perimeter

A class here is a table of methods with a link to its base class. send finds the method at the time of the call: it looks in the class of the object, then in each base class in turn, and calls the first method with the right name. describe is defined once, in Shape, and it sends area and kind back to the same object, so a circle runs its own area and kind, while a square runs its own area and the default kind of Shape. A name that no class in the chain defines is an error at run time.

How it works

Static and dynamic dispatch. A call names an operation, and something must choose the code that runs. The Rust Book states the difference: static dispatch "is when the compiler knows what method you're calling at compile time. This is opposed to dynamic dispatch, which is when the compiler can't tell at compile time which method you're calling."1 Calls to plain functions, to overloaded functions and to generic functions that the compiler copies for each type are static. Calls through a base class, an interface or a trait object are dynamic, because the compiler sees only the declared type and the real type is known only at run time.

Overriding. A subclass can replace a method of its base class with its own version. The C++ reference describes virtual functions as "member functions whose behavior can be overridden in derived classes. As opposed to non-virtual functions, the overriding behavior is preserved even if there is no compile-time information about the actual type of the class."2 Java makes every instance method virtual unless it is static, private or final; the Java specification notes that "a subclass may override a specific method already declared in a parent class so that this overriding method is invoked".3 C#, C++ and Kotlin make methods static by default and dispatch only on methods marked virtual, abstract or open.

Virtual method tables. Compiled languages implement dispatch with a table. Each class has a table of pointers to the code of its virtual methods, and each object holds a hidden pointer to the table of its class. A call loads the table pointer from the object, loads the entry for the method at a fixed slot, and calls the address that it finds. A subclass copies the table of its base, replaces the entries of the methods it overrides and adds entries for new methods, so a slot number is valid for the whole hierarchy. Rust and Go keep the table pointer outside the object: a trait object or an interface value is a pair of a data pointer and a table pointer, and the same value can have a different table for each trait. The C example file builds such a table by hand.

Lookup by name. Python, Ruby, Smalltalk and JavaScript find a method by its name at the time of the call. Python searches the classes of the method resolution order, and JavaScript searches the prototype chain. Because the lookup happens on each call, a program can add or replace a method while it runs. A search for every call would be slow, so implementations cache the result: a method cache stores the method for each pair of class and name, and an inline cache stores at each call site the class that it saw last and the method that it found.

Late binding of self. A method of a base class that calls another method on self or this also dispatches, so the base class can call code that a subclass supplies later. describe in the example calls area, which only the subclasses define. This is called open recursion, and the template method pattern depends on it. It is also a hazard: a change to the calls that a base class makes to its own methods can break a subclass that overrides one of them, which is the fragile base class problem. Constructors are a special case. In C++, during construction and destruction "the function called is the final overrider in the constructor's or destructor's class and not one overriding it in a more-derived class",2 while Java, C# and JavaScript dispatch to the override before the fields of the subclass are set, as the wrong block of the JavaScript file shows.

Single, double and multiple dispatch. In most object-oriented languages only the receiver selects the method: the other arguments choose an overload at compile time, from their static types. The Java example file shows one object that selects two different overloads. To choose on the types of two arguments, a program can dispatch twice, which is the visitor pattern, or use a language with multiple dispatch, such as Common Lisp, Julia or Dylan, where a generic function selects a method from the types of all its arguments. Python's functools.singledispatch dispatches a plain function on one argument. Its documentation says that the decorator will "Transform a function into a single-dispatch generic function", and that "the dispatch happens on the type of the first argument".4

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CIdiom
C#Native
JavaScriptNative
TypeScriptNativeAs JavaScript; methods dispatch through the prototype chain, and the override keyword makes the compiler check that a method overrides a method of the base class.
GoNative
RustNative
KotlinNativeClasses and methods are final unless declared open, an override must say override, and interface methods dispatch on the receiver; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyQueries call functions by name and have no objects with methods in common engines.
BashIdiomA script can build the name of a function from a string, such as the type of a value, and call it, which is dispatch by name with no checks.
PowerShellNativeClasses with methods run on .NET, and a derived class can override a method of its base class; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyHTML is markup with no methods.
CSSDoes not applyCSS selects rules for elements and has no methods to call.
Regular expressionsDoes not applyA pattern has no methods or types to dispatch on.
Language Verdict Mechanism
Python native lookup by name along __mro__; functools.singledispatch
JavaScript native lookup along the prototype chain
TypeScript native as JavaScript; override keyword
Java native instance methods are virtual unless static, private or final
Kotlin native open and override; interfaces
C# native virtual, abstract and override; interfaces; dynamic
Go native calls through interface values
Rust native trait objects with dyn; generics dispatch statically
C idiom structs of function pointers
C++ native virtual functions and vtables
Bash idiom a function name built from a string
PowerShell native class methods on .NET
SQL n/a no objects with methods
Regex n/a no methods
HTML n/a no methods
CSS n/a no methods

Every core language with objects or interfaces has dynamic dispatch as a native feature, and they differ in what dispatches by default. In Python, JavaScript and Java nearly every method call dispatches. In C++, C# and Kotlin a method dispatches only when its declaration says so. In Go and Rust only calls through an interface value or a trait object dispatch, and a call on a concrete type, or through a generic parameter, is static.

Each example file builds the same shapes, with a describe method that calls area, and shows a pitfall of dispatch in that language: a misspelled override in Python, a call from a constructor in JavaScript, an overload that looks like an override in Java, a hidden method in C#, embedding that does not dispatch in Go, a trait that cannot be a trait object in Rust, and object slicing in C++.

PythonGitHub
from abc import ABC, abstractmethod
from functools import singledispatch
import math


class Shape(ABC):
    @abstractmethod
    def area(self): ...

    def describe(self):  # calls area through self, so a subclass decides
        return f"{type(self).__name__} with area {self.area():.2f}"


class Circle(Shape):
    def __init__(self, r):
        self.r = r

    def area(self):
        return math.pi * self.r ** 2


class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2


for s in [Circle(1), Square(2)]:
    print(s.describe())
print([c.__name__ for c in Square.__mro__])  # the order of the lookup


@singledispatch  # dispatch on the type of the first argument
def to_json(x):
    raise TypeError(f"no rule for {type(x).__name__}")


@to_json.register
def _(x: int):
    return str(x)


@to_json.register
def _(x: list):
    return "[" + ",".join(to_json(v) for v in x) + "]"


@to_json.register
def _(x: str):
    return '"' + x + '"'


print(to_json([1, "a", [2, 3]]))
Output
Circle with area 3.14
Square with area 4.00
['Square', 'Shape', 'ABC', 'object']
[1,"a",[2,3]]

This code runs but gives a wrong answer on purpose.

class Shape:
    def area(self):
        return 0.0

    def describe(self):
        return f"{type(self).__name__} with area {self.area()}"


class Square(Shape):
    def __init__(self, side):
        self.side = side

    def aera(self):  # a typo: this method overrides nothing
        return float(self.side ** 2)


print(Square(3).describe())
Output
Square with area 0.0
  • Verdict: native. Every method call in Python looks up the name of the method at run time, first in the object and then in each class of the method resolution order, __mro__, so every method can be overridden. describe is written once in Shape and calls self.area(), which runs the method of the subclass. functools.singledispatch dispatches a plain function on the type of its first argument, which adds operations to types without changing their classes.
  • The wrong block misspells the name of the overriding method. Python finds no area in Square, so it runs the default in Shape, and the area comes out as 0.0. The typing.override decorator lets a type checker report a method that overrides nothing.
#include <cstdio>
#include <memory>
#include <vector>

struct Shape {
    virtual ~Shape() = default;
    virtual double area() const = 0;
    virtual const char* name() const { return "shape"; }
    void describe() const { std::printf("%s with area %.2f\n", name(), area()); }
};

struct Circle final : Shape {
    double r;
    explicit Circle(double r) : r(r) {}
    double area() const override { return 3.141592653589793 * r * r; }
    const char* name() const override { return "circle"; }
};

struct Square final : Shape {
    double side;
    explicit Square(double side) : side(side) {}
    double area() const override { return side * side; }
};

int main()
{
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Circle>(1));
    shapes.push_back(std::make_unique<Square>(2));
    for (const auto& s : shapes) s->describe();
    std::printf("%zu %zu\n", sizeof(double), sizeof(Square)); // the hidden vtable pointer
}
Output
circle with area 3.14
shape with area 4.00
8 16

This code runs but gives a wrong answer on purpose.

#include <cstdio>

struct Shape {
    virtual ~Shape() = default;
    virtual const char* name() const { return "shape"; }
};

struct Circle : Shape {
    const char* name() const override { return "circle"; }
};

void by_reference(const Shape& s) { std::printf("by reference: %s\n", s.name()); }
void by_value(Shape s) { std::printf("by value: %s\n", s.name()); } // copies only the Shape part

int main()
{
    Circle c;
    by_reference(c);
    by_value(c);
}
Output
by reference: circle
by value: shape
  • Verdict: native. A member function declared virtual dispatches on the dynamic type of the object when the program calls it through a pointer or a reference. Each object of a class with virtual functions holds a hidden pointer to the vtable of its class, so Square takes 16 bytes for one double. override makes the compiler check that a function overrides something, and final lets it call the function directly.
  • The wrong block passes a Circle by value as a Shape. The copy contains only the Shape part and has the vtable of Shape, so the call runs Shape::name. This is object slicing. Pass polymorphic objects by reference or by pointer, and delete the copy operations of a base class to make slicing a compile error.
JavaGitHub
import java.util.List;

public class Main {
    sealed interface Shape permits Circle, Square {
        double area();

        default String describe() { // calls area() on the receiver, so each class decides
            return "%s with area %.2f".formatted(getClass().getSimpleName(), area());
        }
    }

    record Circle(double r) implements Shape {
        public double area() { return Math.PI * r * r; }
    }

    record Square(double side) implements Shape {
        public double area() { return side * side; }
    }

    // Overloads: the compiler picks one from the static type of the argument.
    static String kind(Shape s) { return "some shape"; }
    static String kind(Circle c) { return "a circle"; }

    public static void main(String[] args) {
        for (Shape s : List.of(new Circle(1), new Square(2)))
            System.out.println(s.describe());

        Shape s = new Circle(1);
        Circle c = new Circle(1);
        System.out.println(kind(s) + ", " + kind(c)); // same object, different overloads
    }
}
Output
Circle with area 3.14
Square with area 4.00
some shape, a circle

This code runs but gives a wrong answer on purpose.

import java.util.List;

public class Main {
    static final class Point {
        final int x, y;
        Point(int x, int y) { this.x = x; this.y = y; }

        public boolean equals(Point p) { // overloads equals(Object); overrides nothing
            return p != null && x == p.x && y == p.y;
        }

        @Override
        public int hashCode() { return 31 * x + y; }
    }

    public static void main(String[] args) {
        Point a = new Point(1, 2), b = new Point(1, 2);
        System.out.println(a.equals(b));                // static type Point: the overload
        System.out.println(List.of(a).contains(b));     // calls equals(Object): identity
    }
}
Output
true
false
  • Verdict: native. Every instance method in Java is virtual unless it is static, private or final, and interface methods, including default methods such as describe, dispatch on the class of the receiver. Overloads are different: the compiler chooses among kind(Shape) and kind(Circle) from the static type of the argument, so the same circle gives two answers.
  • The wrong block declares equals(Point), which overloads equals(Object) instead of overriding it. The direct call uses the overload, but List.contains calls equals(Object), which still compares identity. An @Override annotation on the method makes the compiler reject it, because it overrides nothing.
#include <stdio.h>

struct shape;

struct shape_vtable {                       /* one table for each class */
    const char *(*name)(const struct shape *);
    double (*area)(const struct shape *);
};

struct shape { const struct shape_vtable *vt; };   /* every object starts with it */
struct circle { struct shape base; double r; };
struct square { struct shape base; double side; };

static const char *shape_name(const struct shape *s) { (void)s; return "shape"; }
static const char *circle_name(const struct shape *s) { (void)s; return "circle"; }

static double circle_area(const struct shape *s)
{
    const struct circle *c = (const struct circle *)s;
    return 3.141592653589793 * c->r * c->r;
}

static double square_area(const struct shape *s)
{
    const struct square *q = (const struct square *)s;
    return q->side * q->side;
}

static const struct shape_vtable circle_vt = { circle_name, circle_area };
static const struct shape_vtable square_vt = { shape_name, square_area };  /* keeps the default name */

static void describe(const struct shape *s)     /* dispatch: load the table, call the slot */
{
    printf("%s with area %.2f\n", s->vt->name(s), s->vt->area(s));
}

int main(void)
{
    struct circle c = { { &circle_vt }, 1.0 };
    struct square q = { { &square_vt }, 2.0 };
    const struct shape *shapes[] = { &c.base, &q.base };
    for (int i = 0; i < 2; i++)
        describe(shapes[i]);
    return 0;
}
Output
circle with area 3.14
shape with area 4.00
  • Verdict: idiom. C has no methods, so programs build dynamic dispatch by hand: a struct of function pointers for each class, and a pointer to it at the start of each object. The cast from struct shape * to struct circle * is valid because base is the first member. This is how C++ compilers lay out single inheritance, and C code bases such as the Linux kernel, with its file_operations table, and GLib's GObject use the same pattern.
  • Nothing checks the casts or the tables. A wrong table in an object, or a function that casts to the wrong struct, compiles and reads the wrong memory.
using System;

Shape[] shapes = { new Circle(1), new Square(2) };
foreach (Shape s in shapes)
    Console.WriteLine(s.Describe());

// dynamic picks the overload at run time from the types of both arguments
foreach (Shape a in shapes)
    foreach (Shape b in shapes)
        Console.WriteLine(Geometry.Meet((dynamic)a, (dynamic)b));

abstract class Shape
{
    public abstract double Area();
    public virtual string Name() => "shape";
    public string Describe() => $"{Name()} with area {Area():F2}";
}

sealed class Circle(double r) : Shape
{
    public override double Area() => Math.PI * r * r;
    public override string Name() => "circle";
}

sealed class Square(double side) : Shape
{
    public override double Area() => side * side;
}

static class Geometry
{
    public static string Meet(Shape a, Shape b) => "two shapes";
    public static string Meet(Circle a, Circle b) => "two circles";
    public static string Meet(Circle a, Square b) => "a circle and a square";
}
Output
circle with area 3.14
shape with area 4.00
two circles
a circle and a square
two shapes
two shapes

This code runs but gives a wrong answer on purpose.

using System;

Square q = new Square();
Shape s = q;
Console.WriteLine(q.Name());
Console.WriteLine(s.Name()); // the same object

class Shape
{
    public string Name() => "shape"; // not virtual
}

class Square : Shape
{
    public new string Name() => "square"; // hides Shape.Name; overrides nothing
}
Output
square
shape
  • Verdict: native. A C# method dispatches at run time only when the base declares it virtual or abstract and the derived class declares it override. Methods are static by default, and interface methods always dispatch. The cast to dynamic moves overload resolution to run time, so Meet chooses its overload from the types of both arguments, which gives multiple dispatch.
  • The wrong block hides a method instead of overriding it. Shape.Name is not virtual, so new in Square declares a second method with the same name, and the static type of the reference chooses between them. Declare the base method virtual and the new one override.
JavaScriptGitHub
class Shape {
  describe() {
    return `${this.constructor.name} with area ${this.area().toFixed(2)}`;
  }
}

class Circle extends Shape {
  constructor(r) { super(); this.r = r; }
  area() { return Math.PI * this.r ** 2; }
}

class Square extends Shape {
  constructor(side) { super(); this.side = side; }
  area() { return this.side ** 2; }
}

for (const s of [new Circle(1), new Square(2)]) console.log(s.describe());

// The lookup walks the prototype chain at the time of the call.
const sq = new Square(3);
console.log(Object.hasOwn(sq, "area"), Object.hasOwn(Square.prototype, "area"),
  Object.hasOwn(Shape.prototype, "describe"));
Square.prototype.area = function () { return -1; }; // change the method for every square
console.log(sq.area());
Output
Circle with area 3.14
Square with area 4.00
false true true
-1

This code runs but gives a wrong answer on purpose.

class Shape {
  constructor() {
    this.label = this.describe(); // dispatches to the subclass too early
  }
  describe() { return "shape"; }
}

class Circle extends Shape {
  r = 2; // a field of Circle: set only after the Shape constructor returns
  describe() { return `circle with radius ${this.r}`; }
}

console.log(new Circle().label);
Output
circle with radius undefined
  • Verdict: native. A method call s.area() looks up the property area on the object and then along its prototype chain, at the time of the call. The methods of a class live on its prototype, which is shared by all instances, so changing Square.prototype.area changes the method for every square, even one made before the change.
  • The wrong block calls an overridable method from a constructor. The call dispatches to Circle.describe, but the fields of Circle are set only after the constructor of Shape returns, so this.r is still undefined. Do not call methods that a subclass can override from a constructor.
package main

import (
	"fmt"
	"math"
)

// Shape is an interface: any type with an Area method satisfies it.
type Shape interface {
	Area() float64
}

type Circle struct{ R float64 }
type Square struct{ Side float64 }

func (c Circle) Area() float64 { return math.Pi * c.R * c.R }
func (s Square) Area() float64 { return s.Side * s.Side }

// Describe takes the interface, so the call s.Area() dispatches at run time.
func Describe(s Shape) string {
	return fmt.Sprintf("%T with area %.2f", s, s.Area())
}

func main() {
	for _, s := range []Shape{Circle{1}, Square{2}} {
		fmt.Println(Describe(s))
	}
	var s Shape = Square{3}
	if sq, ok := s.(Square); ok { // a type assertion recovers the dynamic type
		fmt.Println("side", sq.Side)
	}
}
Output
main.Circle with area 3.14
main.Square with area 4.00
side 3

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

type Base struct{}

func (Base) Name() string { return "shape" }

func (b Base) Describe() string { return "a " + b.Name() } // b is a Base, always

type Circle struct{ Base } // embedding, not inheritance

func (Circle) Name() string { return "circle" }

func main() {
	c := Circle{}
	fmt.Println(c.Name())
	fmt.Println(c.Describe())
}
Output
circle
a shape
  • Verdict: native. A call through an interface value dispatches at run time. The value holds two words, a pointer to a table for its dynamic type and the methods of the interface, and a pointer to the data. A call on a concrete type, such as Square{2}.Area(), is a static call. A type assertion recovers the dynamic type.
  • The wrong block expects embedding to work as inheritance. Circle gets the methods of Base, but when Base.Describe runs, its receiver is the embedded Base, so b.Name() calls Base.Name. Go has no open recursion through embedding. To let the outer type decide, make Describe a function of an interface, as Describe(s Shape) is in the first block.
RustGitHub
use std::f64::consts::PI;
use std::mem::size_of;

trait Shape {
    fn area(&self) -> f64;
    fn name(&self) -> &'static str {
        "shape"
    }
    fn describe(&self) -> String {
        format!("{} with area {:.2}", self.name(), self.area())
    }
}

struct Circle {
    r: f64,
}
struct Square {
    side: f64,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        PI * self.r * self.r
    }
    fn name(&self) -> &'static str {
        "circle"
    }
}

impl Shape for Square {
    fn area(&self) -> f64 {
        self.side * self.side
    }
}

// Static dispatch: the compiler makes one copy of the function for each T.
fn total_static<T: Shape>(xs: &[T]) -> f64 {
    xs.iter().map(|s| s.area()).sum()
}

// Dynamic dispatch: one copy; each call goes through the vtable of the object.
fn total_dyn(xs: &[Box<dyn Shape>]) -> f64 {
    xs.iter().map(|s| s.area()).sum()
}

fn main() {
    let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle { r: 1.0 }), Box::new(Square { side: 2.0 })];
    for s in &shapes {
        println!("{}", s.describe());
    }
    let squares = [Square { side: 1.0 }, Square { side: 2.0 }];
    println!("{:.2} {:.2}", total_dyn(&shapes), total_static(&squares));
    println!("{} {}", size_of::<&Square>(), size_of::<&dyn Shape>());
}
Output
circle with area 3.14
shape with area 4.00
7.14 5.00
8 16

This code does not compile, on purpose. The error is E0038.

trait Show {
    fn show<T: std::fmt::Debug>(&self, extra: T) -> String; // a generic method
}

struct A;

impl Show for A {
    fn show<T: std::fmt::Debug>(&self, extra: T) -> String {
        format!("A {extra:?}")
    }
}

fn main() {
    let v: Box<dyn Show> = Box::new(A);
    println!("{}", v.show(1));
}
  • Verdict: native. A trait object, &dyn Shape or Box<dyn Shape>, is a wide pointer of two words: a pointer to the data and a pointer to the vtable of the concrete type for that trait. The last line shows the sizes on a 64-bit machine. A generic function with a trait bound, such as total_static, uses static dispatch instead, and the program chooses between the two at each use.
  • The failing block puts a generic method in a trait and then uses the trait as dyn Show. A vtable has one slot for each method, but a generic method has a copy for each type T, so it cannot have a slot, and the compiler rejects the trait object with E0038. The Rust Book calls these rules dyn compatibility.
  • Interfaces and protocols. An interface declares the methods that a call through it can dispatch to. See interfaces and subtyping.
  • Multiple dispatch. Common Lisp's CLOS, Julia and Dylan choose a method from the types of all arguments. C# can do this at run time through dynamic.
  • The visitor pattern. Two single dispatches in a row choose code by the types of two objects, in languages that dispatch only on the receiver.
  • Overloading. Overloaded functions share a name and the compiler chooses one from the static types of the arguments. This is static dispatch, often called ad hoc polymorphism. See parametric polymorphism.
  • Pattern matching. A match over the cases of a sum type is the other way to choose code by the kind of a value: it keeps all the cases of one operation in one place, while dispatch keeps all the operations of one case in one class. See sum types and pattern matching.
  • Type classes and traits. Haskell type classes and Rust traits choose an implementation from types, mostly at compile time, and use dictionaries or vtables when the type is known only at run time.
  • Inline caching and devirtualization. JIT compilers cache the target of each call site and inline it, and compilers turn virtual calls into direct calls when they can prove the type. See just-in-time compilation.
  • Object-oriented programming. Dispatch on the receiver is one of the central mechanisms of the paradigm. See object-oriented programming.

Pitfalls

  • An override that overrides nothing. A misspelled name or a different parameter type creates a new method, and the base method still runs. Use @Override in Java, override in C++, C#, Kotlin and TypeScript, and typing.override in Python. The wrong blocks of the Python and Java files show this.
  • Hiding instead of overriding. A method with the same name in a subclass, when the base method is not virtual, is chosen by the static type of the reference. The wrong block of the C# file shows this.
  • Calls from constructors. A constructor that calls an overridable method runs the override on an object whose fields are not set yet, in Java, C# and JavaScript, and runs the base version in C++. Do not call overridable methods from constructors.
  • Object slicing. In C++, copying a derived object into a base object keeps only the base part and its vtable. Pass polymorphic objects by reference or pointer.
  • Fragile base classes. A subclass that overrides one method can depend on how the base class calls its own methods, so a safe change to the base breaks it. Prefer composition, or document which methods call which.
  • Embedding is not inheritance. In Go, a method of an embedded struct calls the methods of the embedded type, not of the outer type. The wrong block of the Go file shows this.
  • Missing virtual destructor. In C++, deleting a derived object through a base pointer without a virtual destructor is undefined behavior, and in practice skips the destructor of the derived class.

Cost

A virtual call costs two dependent loads, the table pointer and the slot, and an indirect branch. When the branch predictor guesses the target, the call costs a few cycles more than a direct call; when the target changes often at one site, a misprediction costs tens of cycles. The larger cost is lost optimization: the Rust Book notes that "Dynamic dispatch also prevents the compiler from choosing to inline a method's code, which in turn prevents some optimizations".1 Each object pays one pointer of memory for its vtable pointer, or each reference pays it in Rust and Go. Lookup by name costs a hash table search on a cache miss and a comparison of the class on a hit. JIT compilers and devirtualization in ahead-of-time compilers remove most of the cost at call sites where one or two types appear.

History

Simula 67, by Ole-Johan Dahl and Kristen Nygaard, introduced classes, subclasses and virtual procedures, which a subclass could redefine. Smalltalk, developed by Alan Kay, Dan Ingalls and others at Xerox PARC in the 1970s, made every operation a message that the receiving object looks up by name at run time. L. Peter Deutsch and Allan Schiffman described the inline cache in their 1984 paper on the Smalltalk-80 implementation, and Urs Hölzle, Craig Chambers and David Ungar added polymorphic inline caches for the Self language in 1991.

Bjarne Stroustrup added virtual functions in 1983, as C with Classes became C++, with the vtable layout that most compiled languages still use. The Common Lisp Object System, adopted into the ANSI standard of 1994, made multiple dispatch on generic functions part of Lisp. Java, in 1995, made instance methods virtual by default, while C#, in 2000, required virtual and override. Go, in 2009, and Rust, in 2015, separated the table from the object and dispatched only through interface values and trait objects. Julia, released in 2012, built its whole design on multiple dispatch.

References

  1. The Rust Programming Language, Using Trait Objects to Abstract over Shared Behavior, Performing Dynamic Dispatch
  2. virtual function specifier, cppreference.com, Explanation; During construction and destruction
  3. The Java Language Specification, Java SE 25 Edition, Chapter 15, 15.12.4.4 Locate Method to Invoke
  4. Python documentation: functools, Higher-order functions and operations on callable objects, functools.singledispatch

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/MZ951T/text.yaml