Friday, August 26, 2005

Multiple Inheritance And The "This"-Pointer

Excellent article on why using C++'s <dynamic_cast> is a good idea when casting multiple-inheritance instance pointers (this is true even if you derive from only one concrete class plus one or more pure virtual classes (=interfaces)). <dynamic_cast> is aware of the different vtable- and memberdata-offsets (due to runtime type information), and will move the casted pointer accordingly.

Some C++ developers tend to keep their C-style casting habits, which will introduce fatal flaws into their code. My recommendation: If you haven't done yet, get to know about the four C++ casting operators, and apply them accordingly. Developers should understand the memory layout of their data types. And what a vtable is. And what a compiler can do, and what not.

If still in doubt, use <dynamic_cast> - it's slower, but safe. Don't forget to check whether the cast was successful, though.