Tuesday, November 17, 2009

How Does Polymorphism Work Under the Hood?



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:

Unweaving the Rainbow, by Richard Dawkins

We are going to die, and that makes us the lucky ones. Most people are never going to die because they are never going to be born. The potential people who could have been here in my place but who will in fact never see the light of day outnumber the sand grains of Sahara. Certainly those unborn ghosts include greater poets than Keats, scientists greater than Newton. We know this because the set of possible people allowed by our DNA so massively outnumbers the set of actual people. In the teeth of these stupefying odds it is you and I, in our ordinariness, that are here.
RichardDawkins.net

Books I am reading this book at the moment:

Atheist

The Out Campaign: Scarlet Letter of Atheism