Skip to main content

Class vtables

Suppose rectangle is a class that extends from shape, and our program creates a rectangle and assigns it to a variable whose type is shape. We have lost the information that this object is really a rectangle, but several Hybrix language features need to recover this information somehow:

  • Virtual functions should invoke the hook of rectangle instead of shape.
  • The class_id() operator should return the ID of rectangle instead of shape.
  • The as operator should give us the actual rectangle variable, or null if the object is not actually a rectangle.

This magic relies on an hidden field called a vtable pointer that the compiler adds to the object's memory block. The term "vtable" is short for virtual method table, familiar from other programming languages such as C++.

The compiler creates a vtable for a Hybrix class...

  • ...if the class contains a hook function, or
  • ...if the class extends from the special class_id_base class, or
  • ...if the class extends from another class with a vtable.

Consequences of vtables

Certain restrictions apply to classes that have vtables:

  • They cannot be used with the located at storage directive.
  • They cannot be used with the inset storage directive.