Search code examples
c++pointersmultiple-inheritance

What is a transverse pointer cast?


I encountered this in Horstmann's Core Java, Volume 1:

C++ has multiple inheritance and all the compications that come with it, such as virtual base classes, dominance rules, and transverse pointer casts...

Core Java Volume I: Fundamentals [Horstmann, Cay S. 2016 Prentice Hall 10th ed. §6.1.3 p. 297]

Now, I am familiar with the other two, but what is a transverse pointer cast? Is it the term for casting a pointer to a base class as a derived class?


Solution

  • I've never seen the term before, but I reckon this is another name for a cross-cast, when you need to cast "across" (rather than "up" or "down") an inheritance graph. Take the following situation:

    // V-shaped inheritance graph
    
    // [ Base1 ]   [ Base2 ]
    //      \         /
    //       \       /
    //      [ Derived ]
    
    struct Base1 { };
    struct Base2 { };
    struct Derived : Base1, Base2 { };
    
    // ...
    
    // Take an object of derived type
    Derived d;
    
    // Upwards conversion, we get its Base1 subobject
    Base1 *b1 = &d;
    

    Now suppose we only have b1, of static type Base1 and dynamic type Derived, and we want to reach the Base2 subobject, that is, convert across the V's branches.

    The issue is, we lost the information that *b1 is actually a subobject of a Derived. It could be a subobject of any other class, or an object on its own. We have to use one of two tools:

    // If we know by other means that b1 is for sure a Derived,
    // walk the graph explicitly through Derived
    Base2 *b2 = /* implicit upwards conversion */ static_cast<Derived*>(b1);
    
    // If Base1 is polymorphic (i.e. has at least one virtual function)
    // Let RTTI do the job and check for errors. Slower but safer.
    Base2 *b2 = dynamic_cast<Base2 *>(b1);