CSC448: Code Generation: Run-Time Storage for Objects III [77/133] |
Corin did not show
Vtables are used to implement dynamic dispatch in object-oriented languages.
A vtable contains an array of pointers to methods that can be invoked for a clazz. There is one vtable per clazz.
Objects keep track of their own methods via a pointer to their vtable. When the compiler is generating code for a method call, it generates code to extract the address of the method to call from the vtable stored in the object.
If edx
contains the address of the vtable for
the clazz, then the layout of a vtable with 3 methods is:
Location | Value |
---|---|
8(%edx)
|
address of method 3 |
4(%edx)
|
address of method 2 |
0(%edx)
|
address of method 1 |
If the contents of one of the vtable words (the address of a
method) is loaded into eax
, then the method can
be called using call *%eax
.
Remember to push the this
pointer when
compiling method calls.
Hunt for examples in:
Vtables are not necessary for this simple language. They become necessary when we introduce subtyping (via subclassing), in which case the compiler does not know the address of the appropriate method to invoke because it does not know the run-time type of an object.
Vtables can also be used to implement run-time type identification.