Search code examples
c++multiple-inheritancedynamic-castreinterpret-cast

Multiple inheritance cast not working as expected


I recently had a problem with casts and multiple inheritance: I needed to cast a Base* to Unrelated*, because a specific Derived class derives the Unrelated class.

This is a short example:

#include <iostream>

struct Base{
    virtual ~Base() = default; 
};

struct Unrelated{
    float test = 111;    
};

struct Derived : Base,Unrelated{};

int main(){
    Base* b = new Derived;
    Unrelated* u1 = (Unrelated*)b;
    std::cout << u1->test << std::endl; //outputs garbage
    Unrelated* y = dynamic_cast<Unrelated*>(b);
    std::cout << y->test << std::endl; //outputs 111
}

The first cast clearly doesnt work, but the second one did work. My question is: Why did the second cast work? Shouldnt dynamic_cast only work for cast to a related class type? I thought there wasnt any information about Unrelated at runtime because it is not polymorphic.

Edit: I used colirus gcc for the example.


Solution

  • dynamic_cast works because the dynamic type of object pointed to by a pointer to its base class is related to Unrelated.

    Keep in mind that dynamic_cast requires a virtual table to inspect the inheritance tree of the object at run-time.

    The C-style cast (Unrelated*)b does not work because the C-style cast does const_cast, static_cast, reinterpret_cast and more, but it does not do dynamic_cast.

    I would suggest avoiding C-style casts in C++ code because they do so many things as opposed to precise C++ casts. My colleagues who insist on using C-style cast still occasionally get them wrong.