Search code examples
c++dynamic-caststatic-cast

Static cast - Cannot cast through virtual inheritance


I was reading about static and dynamic casts along with the differences between them. It states that

static_cast cannot cast through virtual inheritance however dynamic cast can.

I would appreciate it if someone could clarify what this means presumably with a simple example. Thanks


Solution

  • class A {virtual ~A {}}
    class B {virtual ~B {}}
    class C : A, B {}
    
    C o;
    // Now, some implicit conversions:
    A& a = c;
    B& b = c;
    // static casts back:
    C& ca = static_cast<C>(a);
    C& cb = static_cast<C>(b);
    // dynamic casts over the type:
    A& ab = dynamic_cast<A>(b);
    B& ba = dynamic_cast<B>(a);
    

    The dynamic cast can cast accross the hierarchy (or checked to derived types), while the static casts can only cast up and down the hierarchy, where statically proovable sound, aside from the object actually being of the target type.

    Where possible, compilers reduce a dynamic cast to a static one for efficiency.