When is static cast safe when you are using multiple inheritance?

前端 未结 6 598
眼角桃花
眼角桃花 2020-12-10 12:26

I found myself in a situation where I know what type something is. The Type is one of three (or more) levels of inheritance. I call factory which returns B* how

6条回答
  •  执念已碎
    2020-12-10 13:08

    A cross-cast:

    struct Base1 { virtual void f1(); };
    struct Base2 { virtual void f2(); };
    struct Derived : Base1, Base2 {};
    
    Base1* b1 = new Derived();
    Base2* b2 = dynamic_cast(b1);
    

    requires use of dynamic_cast, it cannot be done with static_cast (static_cast should have caused a compile-time error). dynamic_cast will also fail if either base class is not polymorphic (the presence of virtual functions is NOT optional).

    See this explanation on MSDN

提交回复
热议问题