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

前端 未结 6 605
眼角桃花
眼角桃花 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:12

    You can safely upcast if you are sure that the object is actually an instance of that class.

    class Base {};
    class Derived1 : public Base {};
    class Derived2 : public Base {};
    
    int main()
    {
        Base* b = new Derived1;
    
        Derived1* d1 = static_cast(b); // OK
        Derived2* d2 = static_cast(b); // Run-time error - d isn't an instance of Derived2
    }
    

提交回复
热议问题