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
See it run
Follow one call from the caller to the function, and see what each language reads on the way.
Operations
One call, slowly
The caller has a slot number. Watch how it becomes a function.
Step 1 of 5
Before
The caller wants speak. The compiler turned the name into slot 0.
Step 1: Before
def call(obj, slot): table = obj["table"] function = table[slot] return function(obj)DOG = [dog_speak, dog_move]rex = {"table": DOG, "name": "Rex"}call(rex, 0)- Reads
- Two loads, one jump
- Good to know
- One pointer in each object
- Classes known to the caller
- 0
Point at the three boxes: object, table, code. The two arrows between them are the two loads.
In the real world
The same polymorphism under the hood doing real jobs. Pick one and step through it.
A remote with a type check, over a year. Count branches and classes.
Step 1 of 5
Two devices
| Added | Branches | Classes | |
|---|---|---|---|
| 1 | TV, radio | 2 | 2 |
| 2 | |||
| 3 | |||
| 4 | |||
| 5 |
Two branches for on. Nothing wrong yet.
Step 1: Two devices
Common mistakes
The bugs interviewers watch for, with the fix beside each.
No virtual destructor
criticalDeleting through a base pointer is undefined behaviour in C++. Often the derived part is never cleaned up.
Wrongstruct Base { virtual void run(); };Base* b = new Derived();delete b; // undefinedRightstruct Base { virtual void run(); virtual ~Base() = default;};Passing the object by value
criticalThe copy is a base object with the base table.
Wrongvoid hear(Animal a) { a.speak(); }Rightvoid hear(const Animal& a) { a.speak(); }Overriding with a typo
majorAnother signature is another method. The old slot keeps the parent's code.
Wrongclass Dog(Animal): def speek(self): ...Rightclass Dog(Animal): @override # typing, Python 3.12 def speak(self): ...Virtual call in the constructor
majorC++ runs the base version. Java and Python run the subclass on an unfinished object.
Wrongdef __init__(self): self.setup() # overridden belowRightdef make(cls): obj = cls() obj.setup() # after construction return objRewriting for speed without a number
minorA type switch costs branches and design. The call was probably not the problem.
Wrongif type(s) is Circle: ... # faster, I thinkRight# profile first, then split the loop by class
Interview tips
Draw it
- Object, table, code: three boxes
- Two arrows are two loads
- Two objects share one table
Numbers
- 8 bytes for each object
- One table for each class
- Two loads and one jump
Traps
- Virtual destructor
- No value copies
- No hooks in constructors
Words
- Receiver, slot, vptr
- Monomorphic, polymorphic, megamorphic
- Devirtualise, inline, deoptimise