Search code examples
c++inheritancereferencedynamic-castdowncast

Can I Initialize a derived class reference with a base class reference to derived class instance?


I have something like the following:

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

// ...

B b;
const A& aref(b);

// ...

const B& bref(aref);

and when I compile, I get:

no suitable user-defined conversion from "const A" to "const B" exists

Now, if these were pointers rather than references, I would use

bptr = dynamic_cast<B*>(aptr);

but references don't have that. What should I do? Switch to pointers? something else?


Solution

  • You can use dynamic_cast for references, they just throw an exception rather than returning nullptr on failure:

    try {
        const B& bref(dynamic_cast<const B&>(aref));
    }
    catch (const std::bad_cast& e) {
        //handle error
    }
    

    If you absolutely know that aref is actually a B, then you can do a static_cast:

    const B& bref(static_cast<const B&>(aref));