Casting pointer to derived class to reference to pointer to base class

前端 未结 4 1771
星月不相逢
星月不相逢 2021-01-17 02:47

Why I can\'t cast a pointer to derived class to reference to pointer to base class?

struct Base { };
struct Derived : Base { };

int main()
{
    Derived* de         


        
4条回答
  •  佛祖请我去吃肉
    2021-01-17 03:15

    Because a Derived* object is not a Base* object, and it's perfectly possible the two can have different memory layout or value representation (if the alignment requirements of Base and Derived differ, for example). Since one is not the other, static_cast is powerless to perform the conversion.

    If you know what you're doing and know that the type pun is OK, use the tool for type punning — reinterpret_cast:

    reinterpret_cast(derived);
    

    And be aware of any consequences of misuse (as always goes with reinterpret_cast). Notice in particular that per C++11 3.10/10, any access through the result of the cast will be Undefined Behaviour as far as the standard is concerned (although your compiler might possibly give stronger guarantees).

    Notice that in the general case, a cast from Derived* to Base* need not be a no-op. It can involve an address shift if multiple inheritance is involved, for example.

提交回复
热议问题