Can a pointer of a derived class be type cast to the pointer of its base class?

前端 未结 4 572
粉色の甜心
粉色の甜心 2021-01-05 09:54

The pointer of derived class returned by new can be type cast to the pointer of its base class.

Is this true or false?

I know dynamic_cast can be used to cas

4条回答
  •  时光说笑
    2021-01-05 10:07

    That's true if derived class inherits 'publicly' and 'non-virtually' from base:

    You can't convert Derived* to Base* neither implicitly nor using static_cast/dynamic_cast (C-cast will do the job, but you should think twice before use this hack!);

    class Base { };
    
    class Derived : protected Base { };
    
    int main()
    {
       Base* b = new Derived(); // compile error
    }
    

    Also don't work if base class is ambiguous:

    class Base { };
    
    class Derived1 : public Base { };
    class Derived2 : public Base { };
    
    class MostDerived : public Derived1, Derived2 { };
    
    int main()
    {
       Base* b = new MostDerived(); // won't work (but you could hint compiler
                                    // which path to use for finding Base
    }
    

    Edit: added code samples, added ambiguous use case, removed virtual inheritance example.

提交回复
热议问题