AlgoViz

Polymorphism under the hood

hard 45 min

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

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 5:10

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

maincallerknowsslot 0rexDogtableDOGnameRexDOGtable of Dog[0]dog_speak[1]dog_movedog_speakfunctionself?

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

AddedBranchesClasses
1TV, radio22
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

    critical

    Deleting through a base pointer is undefined behaviour in C++. Often the derived part is never cleaned up.

    Wrong
    struct Base { virtual void run(); };Base* b = new Derived();delete b;            // undefined
    Right
    struct Base {    virtual void run();    virtual ~Base() = default;};
  • Passing the object by value

    critical

    The copy is a base object with the base table.

    Wrong
    void hear(Animal a) { a.speak(); }
    Right
    void hear(const Animal& a) { a.speak(); }
  • Overriding with a typo

    major

    Another signature is another method. The old slot keeps the parent's code.

    Wrong
    class Dog(Animal):    def speek(self): ...
    Right
    class Dog(Animal):    @override            # typing, Python 3.12    def speak(self): ...
  • Virtual call in the constructor

    major

    C++ runs the base version. Java and Python run the subclass on an unfinished object.

    Wrong
    def __init__(self):    self.setup()         # overridden below
    Right
    def make(cls):    obj = cls()    obj.setup()          # after construction    return obj
  • Rewriting for speed without a number

    minor

    A type switch costs branches and design. The call was probably not the problem.

    Wrong
    if type(s) is Circle: ...   # faster, I think
    Right
    # 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