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

前端 未结 4 1728
星月不相逢
星月不相逢 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:11

    For your Error only change this

    static_cast<Base*&>(derived);
    to 
    static_cast<Base*>(derived);
                    ^^
    

    See here http://ideone.com/1QuMLK

    0 讨论(0)
  • 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<Base*&>(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.

    0 讨论(0)
  • 2021-01-17 03:23

    if you want a reference you need to do

    Base* ptr = static_cast<Base*>(derived);
    Base &ref = *ptr;
    

    you cant cast a pointer to a reference - they are quite different things

    0 讨论(0)
  • 2021-01-17 03:29

    As per your comment:

    "No, it is not an academic question. I need to call a function taking as argument Base*&"

    The correct way to resolve this is to create a new pointer variable of the appropriate type, and pass that (or rather, a reference to it) to the function in question:

    struct Base { };
    struct Derived : Base { };
    
    int main()
    {
        Derived* derived = nullptr;
        Base* base = static_cast<Base*>(derived);
        my_function(base); // takes a Base*& argument
    
        // If you need the pointer value and are sure that
        // it's a Derived* type:
        derived = static_cast<Derived*>(base);
    }
    

    Note that you would likely have received this answer sooner if you had included the pertinent information (from the comment I quoted above) in the question itself.

    0 讨论(0)
提交回复
热议问题