Search code examples
c++referencepolymorphismpass-by-referenceupcasting

cannot convert from 'DerivedClass *' to 'BaseClass *&'


I try the following code, and get a compilation error.

class A {};
class B : public A {};

void f(A*& p) {}

int
main()
{
    B* pB;
    f(pB); // cannot convert argument 1 from 'B *' to 'A *&'

    return 0;
}

How to work around to make f(pB) call the f(A*&p) function?


Solution

  • A pointer variable passed to a non-const reference must match the same data type as the reference. The function is expecting a reference to an A* pointer so that is what you have to give it. If you have a B* pointer to start with, assign it to an A* variable first (since B derives from A):

    B* pB = ...;
    A* pA = pB;
    f(pA);
    

    But if the function modifies the pointer it is passed, it will modify pA not pB. If you need it to modify pB instead, you will have to re-think your design.

    If you qualify the parameter as const, thereby guaranteeing that f won't modify it, then there is no problem:

    void f(A* const & p) { /* Compiles fine */ }