1

I use dynamic cast for safety:

here is the code I use with pointers:

XYZ xyz = dynamic_cast<XYZ*>(abc);
if (xyz == nullptr)
{
    // TODO handle error
}

Now is there a way to do the same but with references:

XYZ& xyz = dynamic_cast<XYZ&>(abc);
if (xyz == nullptr)
{
    // TODO handle error
}

this code doesn't compile but I am asking is there a way to do that in a similar fashion.

mmohab
  • 2,303
  • 4
  • 27
  • 43

2 Answers2

6

dynamic_cast throws an exception on failure if used with references. To handle failure, catch the exception:

try {
    XYZ& xyz = dynamic_cast<XYZ&>(abc);
}
catch (std::bad_cast& e) {
    //handle error
}
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
3

Yes, but since you're casting to a reference, nullptr is not a possible outcome. Instead, if the dynamic type of abc is not convertible to XYZ, the cast will throw std::bad_cast.

dlf
  • 9,045
  • 4
  • 32
  • 58