Not being happy just using Polymorphism (and other OO mechanisms) I wanted to know exactly how it works at a lower level. This is well documented and has been for some time but I like to write my own programs to truly understand what is going on. It can be a painful way to learn, full of frustrations but in the end you truly understand how these seemingly 'magical' (although we all know they aren't) mechanisms work. I'll start with a quick introduction about virtual function tables (VFT) and move on to the example after.
C++ implements dynamic dispatch using virtual function tables (VFTs). VFTs were first used by Simula [DM73] and today are the preferred C++ dispatch mechanism [ES90]. The basic idea of VFTs is to determine the function address by indexing into a table of function pointers (the VFT).
Each class has its own VFT, and each instance contains a pointer to the appropriate VFT. Function names (selectors) are represented by numbers. In the single-inheritance case, selectors are numbered consecutively, starting with the highest selector number used in the superclass. In other words, if a class C understands m different messages, the class’ message selectors are numbered 0..m-1. Each class receives its own dispatch table (of size m), and all subclasses will use the same selector numbers for methods inherited from the superclass. The dispatch process consists of loading the receiver’s dispatch table, loading the function address by indexing into the table with the selector number, and jumping to that function.
I don't like theory alone - most developers learn by doing and not saying. So I wrote the following little C program to illustrate how polymorphism would work using offsets.
No comments:
Post a Comment