Virtual Method Tables

Now we address the question of how virtual methods work, which is another interesting mystery. When a message it sent to a polymorphic variable, the compiler cannot tell which of many different method bodies will be the function that is finally executed. To accomplish this, every object maintains a pointer to a table, called the virtual method table. This is simply a table of pointers to functions. Methods are then identified by a fixed address into this table.

Using this scheme, a method call is translated internally into an index into the virtual method table, which is then dereferenced to get the actual function to call. Note that the receiver is also passed along as a hidden first parameter, the this or self value in the method.

[audio] [real] Text to accompany slide5, in Chapter 21 of An Introduction to Object-Oriented Programming