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

前端 未结 4 1753
星月不相逢
星月不相逢 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: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(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(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.

提交回复
热议问题