Object-oriented languages permit procedures and data to be packaged together into objects.
Example (C++)
Note that class functions (like show) have implicit access to the data elements of the class (like contents).
Naive Implementation
Just add implicit this pointer parameter to each class function. Then can represent class in ordinary C (or close).
Inheritance
If a class B inherits from another class A, B contains all the data fields and functions that A does, plus more. Any B object can be used wherever an A object can be used.
Example: fancytext is subclass of text.
Represent each subclass object by record that extends superclass object.
(Multiple inheritance is considerably harder.)
Inheritance (cont.)
Superclass functions work on subclass objects too,
because offsets of data fields they can see are the same!
Subclass functions work only on subclass objects,
since they may reference fields that only exist in subclass:
Since superclass and subclass have different
sizes, direct assignment or pass-by-value
of object records won't work properly. Instead, should
always manipulate pointers to class records.
(C++ is unusual in not requiring this implicitly anyhow.)
Virtual Functions
Sometimes it is appropriate to redefine the behavior of a function within a subclass:
Invokes fancytext_show if x is actually a fancy text; otherwise invokes text_show.
We can't tell at compile time which function should be invoked! Solution: Function Pointers in Objects
Dispatch Tables
If there are many virtual functions in class, it's better to separate out the function pointers for each defined subclass into a function dispatch table, which is pointed to from each object record for that subclass.
The tables for all related classes are organized so that a given function always appears at the same table offset.
Advantage: saves space in object records (though still uses lots of duplicate space in deep class hierarchies).
Disadvantage: virtual function calls require an extra dereference.
This is essentially the implementation model used by C++, Java, Smalltalk, etc.
Multiple inheritance (C++) or interfaces (Java) requires more work, because we can't
maintain field or function entries in the same slot as the superclass when there
are multiple superclasses!