AlgoViz

Polymorphism under the hood

hard 45 min

One line, device.turn_on(), runs different code for different objects.

Watch lesson5:10

Where it shows up

The same pattern appears across everyday software.

  • Itanium C++ ABI

    The document that GCC and Clang follow on most systems. It defines where the virtual pointer sits, the order of the table, and the thunks.

  • Linux virtual file system

    `struct file_operations` is a table of function pointers written by hand in C. Each file system fills it, and the kernel calls read through it.

  • CPython type slots

    Special methods such as `__len__` fill function slots of the type. The data model says that they are looked up on the type, not on the object.

  • CPython 3.11 and later

    PEP 659 replaces an instruction that keeps seeing the same type by a specialised one, with a check in front.

  • V8 (Chrome, Node.js)

    Objects have shapes, and property reads have inline caches that remember the shape and the place.

  • Go interfaces

    Russ Cox describes the interface value as two words: one points to an itable for this pair of types, the other to the data.

  • Rust trait objects

    The Rust book contrasts generic code, where the method is known, with `dyn` trait objects, where pointers inside the trait object are used at run time.

  • .NET virtual stub dispatch

    The runtime's design document describes dispatch stubs for call sites with one type and resolve stubs for polymorphic ones, with back patching.

  • Swift compiler

    Its optimisation tips advise `final` and `private`, so that the compiler can remove dynamic dispatch.

  • GCC

    `-fdevirtualize` and `-fdevirtualize-speculatively` turn virtual calls into direct calls when the target is known or likely.