Search code examples
c++pointersmultiple-inheritancevtablememory-alignment

How to align pointers when dealing with multiple-inheritance?


Say we have a concrete class A, and an abstract class B.

Consider a concrete C, that inherits from both A and B, and implements B:

class C : public A, public B  
{  
/* implementation of B and specific stuff that belongs to C */  
};

Now I define a function which signature is void foo(B* b);

This is my code, I can assume that every pointers to B are both A and B. In foo's definition, how to get a pointer to A? A nasty but working trick is to align back pointers like so:

void foo(B* b)  
{  
    A* a = reinterpret_cast<A*>(reinterpret_cast<char*>(b) - sizeof(A));
    // now I can use all the stuff from A  
}

Keep in mind that C does not have a super type and actually, there are many classes akin to C which only are A and B. Feel free to question both my logic and this sample of design as well but the question is only concerning pointers alignment.


Solution

  • void foo(B* b)  
    {  
        //A* a = reinterpret_cast<A*>(reinterpret_cast<char*>(b) - sizeof(A)); // undefined behaviour!!!!
        A* a = dynamic_cast<A*>(b);
        if (a)
        {
           // now I can use all the stuff from A  
        }
        else
        {
           // that was something else, not descended from A
        }
    }
    

    Forgot to say: in order to make work dynamic cast both A and B should have virtual function(s) or at least virtual destructors. Otherwise there is no legal way to do that type conversion.