TITLE: Casting across multiple base classes PROBLEM: bhood@netcom.com (robert hood) [ I'm posting this for a friend. Please send any replies directly to him at hxg@evolving.com. Thanks! ] I am experiencing a problem casting accross multiple base classes. Here is the inheritance hierarchy: -------- -------- | baseA | | myBase | -------- -------- | | | | ----------- | | derivedA | | ----------- | | | | | | | | ----------- ---------------| myClass | ----------- BaseA and derivedA are part of a third party software package we are integrating into our inheritance hierarchy. DerivedA does not declare baseA as a virtual base class so having myBase inherit from baseA is not an option, bummer! The problem I am having is that I need to perform operations on myBase through a pointer to baseA. NOTE: Operations are to be performed on myBase in order to hide casting down to myClass. There will be many possible variations of myClass and casting will be impossible at run time. RESPONSE: clamage@Eng.Sun.COM (Steve Clamage), 9 Feb 95 There is no relationship from baseA to myBase, so a cast from baseA* directly to myBase* cannot work. The compiler must assume you are punning types, and that the baseA object and myBase object begin at the same address, which they do not. (A cast tells the compiler, "Trust me, I know what I'm doing." When you lie, programs crash.) Given a baseA*, the only way you can access myBase is by downcasting from baseA to myClass, then back up to myBase: baseA bp = ....; ((myBase*)(myClass*)bp)->myBaseFunction(); Why can't the compiler figure this out by itself? Suppose we have baseA ba; baseA* bap = &ba; myBase mb; myBase* mbp = &mb; // mbp and bap point to unrelated objects ((myBase*)bap)->myBaseFunction(); How can the compiler know that this example is invalid while your code is OK? Further suppose we have another hierarchy class otherClass : derivedA, someClass, myBase { ... }; Now if I cast from baseA* to myBase*, which offset does the compiler assume for myBase within the entire object? The offset of myBase in myClass, or the offset of myBase in otherClass? If you have RTTI available, you could in principle use it, but I recommend very strongly against that solution. It would be equivalent to putting a "whatami" key in each object, and writing switch statements. Error-prone, unreadable, unmaintainable. You will have to re-think the problem, and decide what you actually need. Generally when you are at an impasse, it is because you have overspecified the problem, or have created a problem which is not part of the job you need to get done.