Polymorphism under the hood
hard 45 minOne line, device.turn_on(), runs different code for different objects.
Video lesson · Chapter 1 of 6
Make a prediction
Polymorphism under the hood
1:02Reel
Theory
Read or listen first. About 2 min.
What it is
Polymorphism comes from Greek: *poly* is many, *morph* is form. One piece of code works with many kinds of object. Polymorphism shows how to design with it. This page shows how the machine finds the right method.
There are two families. Static polymorphism is settled by the compiler: overloading, operator overloading, and generics and templates. Dynamic polymorphism is settled while the program runs: overridden methods, virtual functions, interface methods. The second kind needs a lookup, and the lookup is the subject here.
The usual tool in compiled languages is the virtual method table, in short vtable. It is a list of function addresses that belongs to a class. Every object carries one hidden pointer, the vptr, to the table of its class. A call reads the pointer, reads one slot, and jumps. Other languages search dictionaries or prototype chains and then remember the answer.
Why it exists
The caller was compiled before the class existed. A remote control written last year must work with a heater written today. So the address of the method cannot be in the caller. It must be found through the object.
Knowing the mechanism explains things that look like magic or like bugs: why a base class in C++ wants a virtual destructor, why a virtual call in a constructor surprises people, why passing an object by value cuts off its subclass, and why some hot loops are slow.
It also gives you numbers to reason with: one pointer for each object, one table for each class, two memory reads and one indirect jump for each call. With them you can say when dispatch matters and when it does not.
A short history
1967
Simula 67 has classes, subclasses and virtual procedures.
1984
Deutsch and Schiffman describe inline caching for Smalltalk-80 at the POPL conference.
1991
Hölzle, Chambers and Ungar publish polymorphic inline caches at ECOOP, from their work on Self.
1999
The Java HotSpot virtual machine is released. It compiles hot code while it runs, and can turn a virtual call into a direct one.
2021
PEP 659 describes the specializing adaptive interpreter, the base of the faster CPython 3.11.
Words to know
- Dynamic dispatch
- Choosing the method at run time, from the class of the object.
- Late binding
- The name is tied to the code late, when the call happens.
- Vtable (VMT)
- A list of function addresses, one list for a class.
- Vptr
- The hidden pointer in an object to the table of its class.
- Slot
- The fixed position of a method in the table. The caller knows only this number.
- Receiver
- The object before the dot. Its class decides.
- MRO
- Method resolution order: the list of classes that Python searches.
- Devirtualisation
- The compiler proves or guesses the class and calls the method directly.
- Inline cache
- A note at the call site: last time the class was this, and the method was that.
- Object slicing
- In C++, copying a derived object into a base variable. The derived part is lost.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Call. The caller knows a slot
Understand it
Start here
The coach, the headbands and the boards
A coach calls a number. Each child does something else. The coach keeps no list of children, and nobody asks the coach what to do. Watch where the information lives.
The smell
What people write without it
You have four devices: a TV, a radio, a fan and a light. One remote should switch on any of them, and each switches on in its own way. Without dispatch, the remote has to know all of them.
def turn_on_device(device): if device["type"] == "tv": return show_picture(device) elif device["type"] == "radio": return play_sound(device) elif device["type"] == "fan": return spin_blades(device) elif device["type"] == "light": return emit_light(device) # a new device: edit here, and a forgotten one fails in silenceWith dispatch
device.turn_on()and nothing else- A new device is a new class
- The remote needs no new test
- A missing method is found by the compiler, or when the object is made
With an if chain
- The function knows every type
- Every operation repeats the chain
- A forgotten branch is found by users
- Two people edit the same lines
The remote that knows too much
1/3One device
It starts well. The remote calls the TV.
uses
How it works
Two small structures
Objects, tables, functions
1/4Objects
Two dogs and a cat. Each has its own name and one hidden field.
uses
The four steps of one call
The same four steps as a compiler writes them
- 1
Fetch the pointer
table = object->vptr. Usually at the start of the object, offset 0. - 2
Find the place
offset = slot * sizeof(pointer). The slot is a constant, so the compiler has already done this. - 3
Load the address
function = table[slot]. The second read from memory. - 4
Jump
function(object, arguments). The object travels along asthisorself.
Four facts about the table
| Fact | Why it is so |
|---|---|
| One table for a class, shared by its objects | Methods do not differ between two dogs, so the list is stored once |
| Made by the compiler in C++, and placed in memory that is not written to later. In Java it is made when the class is linked | The contents are fixed once the class is known |
| Each method has a fixed slot | The caller is compiled with the number |
| A subclass starts with the parent's list and replaces entries. New methods go to the end | Code for the parent must work with the same numbers |
Binding
Which calls are looked up?
Static and dynamic binding
| Question | Static binding | Dynamic binding |
|---|---|---|
| Decided | When the program is compiled | When the line runs |
| Decided by | The type of the variable | The class of the object |
| C++ | Functions without virtual | virtual and override |
| Java | static and private methods, constructors, super.m() | All other instance methods |
| Cost | A direct jump, and it can be inlined | Two reads and an indirect jump, unless optimised |
| A subclass can change it | No, only hide it | Yes |
final method in Java is called with the same bytecode as others. Nothing can override it, so the JVM may call it directly.Will this call be dispatched?
#include <iostream>class Animal {public: virtual void speak() { std::cout << "Animal speaks\n"; } virtual void move() { std::cout << "Animal moves\n"; } void eat() { std::cout << "Animal eats\n"; } // not virtual: no slot virtual ~Animal() = default; // needed, see below};class Dog : public Animal {public: void speak() override { std::cout << "Dog barks\n"; } void move() override { std::cout << "Dog runs\n"; } void eat() { std::cout << "Dog eats\n"; } // hides, does not override};class Cat : public Animal {public: void speak() override { std::cout << "Cat meows\n"; }};int main() { Animal* animals[] = {new Animal(), new Dog(), new Cat()}; for (Animal* a : animals) { a->speak(); // Animal speaks, Dog barks, Cat meows a->move(); // Animal moves, Dog runs, Animal moves a->eat(); // Animal eats, three times delete a; // runs the right destructor }}speak and move have slots. eat has none, so the type of the pointer decides.Four languages
Same idea, different search
C++
Only
virtualfunctions are dispatched. The standard does not demand a vtable, and all common compilers use one. Several base classes are allowed.Java
Instance methods are virtual unless private, static or final in effect. The JVM keeps a method table for classes and a second structure for interfaces.
Python
All methods are looked up by name, in dictionaries, along the MRO. Any object with the method will do: duck typing.
JavaScript and TypeScript
A method is a property. If the object does not have it, the engine follows the prototype chain.
classis mostly a nicer way to write this.
class Animal: def speak(self): return "Animal speaks" def move(self): return "Animal moves"class Dog(Animal): def speak(self): return "Dog barks" def move(self): return "Dog runs"class Cat(Animal): def speak(self): return "Cat meows"print([c.__name__ for c in Cat.__mro__]) # ['Cat', 'Animal', 'object']print(Dog.speak is Animal.speak) # False: overriddenprint(Cat.move is Animal.move) # True: inheriteddef find(obj, name): """What obj.name does for a plain method.""" if name in vars(obj): # the object's own dictionary return vars(obj)[name] for cls in type(obj).__mro__: # then the classes, in order if name in vars(cls): return vars(cls)[name].__get__(obj) # bind: self is filled in raise AttributeError(name)mimi = Cat()print(find(mimi, "speak")(), "/", find(mimi, "move")())mimi.speak = lambda: "Mimi purrs" # shadows the classprint(mimi.speak(), "/", find(mimi, "speak")())The full rule has one more step: a data descriptor on the class, such as a property, is taken before the object's own dictionary. And special methods such as __len__ are looked up on the class only: len(x) does not see a __len__ that you put on the object.
abstract class Animal { speak(): void { console.log("Animal speaks"); } move(): void { console.log("Animal moves"); }}class Dog extends Animal { override speak(): void { console.log("Dog barks"); } override move(): void { console.log("Dog runs"); }}class Cat extends Animal { override speak(): void { console.log("Cat meows"); }}const cat = new Cat();Object.getPrototypeOf(cat) === Cat.prototype; // trueObject.getPrototypeOf(Cat.prototype) === Animal.prototype; // trueObject.hasOwn(cat, "speak"); // falseObject.hasOwn(Cat.prototype, "speak"); // truefor (const a of [new Dog(), cat] as Animal[]) { a.speak(); // Dog barks, Cat meows a.move(); // Dog runs, Animal moves console.log(a.constructor.name, a instanceof Animal);}The prototype chain of one cat
cat.move() is found two steps up. cat.fly() reaches null, and calling undefined is an error.abstract class Animal { public void speak() { System.out.println("Animal speaks"); } public void move() { System.out.println("Animal moves"); } public final void breathe() { System.out.println("Animal breathes"); }}class Dog extends Animal { @Override public void speak() { System.out.println("Dog barks"); } @Override public void move() { System.out.println("Dog runs"); }}class Cat extends Animal { @Override public void speak() { System.out.println("Cat meows"); }}class PolymorphismDemo { public static void main(String[] args) { Animal[] animals = {new Dog(), new Cat()}; for (Animal a : animals) { a.speak(); // by the object a.move(); a.breathe(); // always the same method System.out.println(a.getClass().getName()); // Dog, then Cat } }}invokevirtual for classes, invokeinterface for interfaces. The declared type is Animal, the real class is Dog.Where each language keeps the pieces
| Hidden pointer | Table | Search at run time | |
|---|---|---|---|
| C++ (usual ABI) | vptr, first in the object | One vtable, more with several bases | None, one slot |
| Java (HotSpot) | Class word in the object header | vtable in the class, itable for interfaces | None for classes, a short search for interfaces |
| Python | type(obj) | Dictionaries, and slots for special methods | Walk of the MRO, cached |
| JavaScript (V8) | Hidden class, also called shape | Prototype objects | Walk of the chain, cached at the call site |
| Go | In the interface value, not in the object | itab for a pair of interface and type | None after the itab is made |
Rust dyn Trait | In the reference, not in the object | vtable for a pair of trait and type | None, one slot |
Cost
What does a virtual call cost?
Two reads from memory and an indirect jump. If the table and the code are in the cache and the processor guesses the target well, you will not notice it. The larger cost is what the compiler cannot do: a method that is not known cannot be copied into the caller, so nothing around it can be simplified either.
Counting for one million objects on a 64-bit machine
| Thing | Cost | Arithmetic |
|---|---|---|
| Pointers | 8 MB | 1,000,000 x 8 bytes |
| Table with 5 methods | 40 bytes and a little more | 5 x 8, once for the class |
| A 4-byte int and a vptr | 16 bytes for each object | 8 + 4, rounded up to 16 |
| The same int without virtual | 4 bytes | No pointer |
sizeof and clang. Nine virtual methods also give 16: the object holds one pointer, not nine.A profiler shows that 30% of the time is in a loop with a virtual call. What do you do?
BreaksReplace all virtual calls in the program
- How
- Type codes and switch statements everywhere.
- Limit
- Code gets worse where it was never slow, and the switch has branches that miss too.
- Choose when
- Never as a first step.
WorksMark classes final
- How
finalin C++ and Java,sealedin C#. The compiler may call directly.- Limit
- Helps only where the exact type is visible. You also close the class.
- Choose when
- A cheap try when nobody extends the class.
StrongMove the decision out of the loop
- How
- Group the objects by class and process a group at a time. One dispatch for a group, and a simple loop inside.
- Limit
- The order of work changes, and the data layout too.
- Choose when
- Measured hot loops: drawing, physics, parsing.
Neighbours
How it fits with other ideas
| Idea | Connection |
|---|---|
| Method overriding | Overriding is the rule you write. The table is how it is kept. |
| Open/closed | The slot is the contract. New tables extend, the caller stays closed. |
| Destructors | A destructor is found through a slot too, if it is virtual. |
| Multiple inheritance | More than one base means more than one pointer in the object. |
| Strategy | A table with one slot, chosen by hand. |
| Visitor | Two dispatches in a row, so that two classes decide together. |
Summary
The whole topic in one minute.
A class owns a table of functions. An object owns a pointer to that table. A call knows a slot number. Read the pointer, read the slot, jump, and pass the object along. A subclass starts with a copy of the table and replaces what it overrides.
Languages differ in the search and agree on the idea. C++ and Java use tables, Python walks the MRO, JavaScript walks prototypes. All fast ones remember answers. The cost is small, and the important loss is inlining, so look at it only in hot loops that you measured.
- One table for a class and one hidden pointer for an object
- The caller is compiled with a slot number and never with a class name
- A subclass copies the parent's table and replaces what it overrides
- Python walks the MRO, JavaScript walks prototypes, and both cache the result
- The main cost is the lost inlining. Engines win it back with inline caches and devirtualisation
- In C++: virtual destructor in base classes, no virtual call in constructors, no copy by value
Sources
- Itanium C++ ABI
- isocpp.org FAQ: virtual functions
- C++ Core Guidelines (C.35, C.82)
- JVM specification, chapter 6: invokevirtual and invokeinterface
- Python data model
- PEP 659: Specializing Adaptive Interpreter
- Mathias Bynens: Shapes and Inline Caches
- Russ Cox: Go Data Structures: Interfaces
- The Rust book: trait objects
- Linux kernel: overview of the virtual file system
- .NET: Virtual Stub Dispatch
- Wikipedia: Inline caching
- Wikipedia: Simula