May 07, 2003

Simulated Dynamic Binding

I'm going to try and write a bit more about WTL in the future, and this is the first mini-article. Many people who use WTL ask why so many classes need to be defined like this:

class MyWindow : public CWindowImpl<MyWindow>

The base class then calls methods (possibly in your class) by doing this:

T* pT = static_cast<T*>(this);

This effectively provides a compile-time virtual function. If I implement SomeFunction in my class then it will be called by this code. Otherwise, the code in the base-class will be called. Some of the reasons that this is beneficial over using virtual functions are:

  1. Two levels of runtime indirection saved (virtual function pointer + virtual function table).
  2. static_cast calculations can be performed at compile time - no runtime cost.
  3. Possibly saves on having any virtual function pointer and vtable - saving space (albeit minimal savings).
  4. The base class doesn't actually need to define the method - like a pure virtual function.
  5. You can call static methods and public members (both static and non-static).

There are a number of names for this technique, the common one (on the WTL list at least) seems to be "simulated dynamic binding".

According to Igor Tandetnik on the WTL list, the method is probably first mentioned in "Curiously Recurring Template Patterns", C++ Report, February 1995 by James O. Coplien. Apparently Coplien attributes the pattern to others. The pattern is reproduced in the book "C++ Gems".

I've put this mini-article together having read through the recent discussion on the WTL yahoo group. My particular thanks to Daniel Bowen, Igor Tandetnik and Tim Tabor for information that I've used in this post.

Posted by Simon at May 7, 2003 11:34 PM