Search code examples
c++dynamic-castreference-type

dynamic cast for references


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.


Solution

  • 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
    }