VTables and Object-Oriented Assembler

The usual technique for getting something that looks object-oriented in non-object-oriented languages is to fill a structure with function pointers, and have those functions take the structure itself as an argument. This works just fine in assembler, of course (and doesn't really require anything more than your traditional jump-indirects), but it's also possible to use a lot of the standard optimizations that languages such as C++ provide.

The most important of these is the vtable. Each object type has its own vtable, and it's a list of function pointers for all the methods that type provides. This is a space savings over the traditional structs-with-function-pointers approach because when you have many objects of the same class, you only have to represent the vtable once. So that all objects may be treated identically, the vtable location is traditionally fixed as being the first entry in the corresponding structure.

Virtual method invocation takes an object pointer (traditionally called self or this) and a method index and invokes the approprate method on that object. Gee, where have we seen that before?

sprite'vtable:
    jsr do'jump'table
    .word sprite'init, sprite'update, sprite'render

We mentioned before that vtables are generally the first entries in objects. We can play another nasty trick here, paying an additional byte per object to have the vtable be not merely a pointer to its vtable routine, but an actual jump instruction to it. (That is, if an object is at location X, then location X is the byte value $4C, representing JMP, location X+1 is the low byte of the vtable, and location X+2 is the high byte of the vtable.) Given that, our invokevirtual function becomes very simple indeed:

invokevirtual:
    sta this
    stx this+1
    jmp (this)

Which, combined with all our previous work here, takes the this pointer in .AX and a method identifier in .Y and invokes that method on that object. Arguments besides this need to be set up before the call to invokevirtual, probably in some global argument array somewhere as discussed back in the Chapter called Structured Programming.