0

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?

einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

5

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));
TartanLlama
  • 63,752
  • 13
  • 157
  • 193