TITLE: downcasting from virtual base PROBLEM: delaube@ibm.net [...] Why can't I explictly downcast any longer once multiple inheritance is introduced into my heirarchy? RESPONSE: wil@ittpub.nl (Wil Evers), 10 Nov 95 The rule is that you can't downcast from a virtual base class to a derived class. The reason is that once virtual base classes are used the layout of a derived object accessed through a base class pointer is unknown at compile time. To get around this, derived class objects with virtual bases carry a hidden pointer to get to the base class representation. But since the `virtualness' of the inheritance is not a property of the base class, base class objects do not carry a pointer to get to the derived class representation. The dynamic_cast operator will correctly cast to the derived class object if possible. If you don't have a compiler that supports dynamic_cast, a common workaround is to define virtual functions to do the casting for you: class Left; class Right; class Merge; class Split { public : virtual Left *castToLeft() { return 0; } virtual Right *castToRight() { return 0; } virtual Merge *castToMerge() { return 0; } }; class Left : public virtual Split { public : virtual Left *castToLeft() { return this; } }; class Right : public virtual Split { public : virtual Right *castToRight() { return this; } }; class Merge : public Left, public Right { public : virtual Merge *castToMerge() { return this; } }; void f(Split *ps) { Merge *pm = ps->castToMerge(); if (pm) { // call member functions of Merge } } It looks ugly and requires the base class to know about its derived classes, but it works. [ This is indeed ugly. It violates the Open-Closed Principle in that adding another derived class will require modifying the base class. Fortunately (or unfortunately), the dynamic_cast<> operator is being implemented in more compilers. (It will be available in MSVC++ this month). -adc ]