Search code examples
c++dynamic-cast

Is target type necessary in dynamic casting?


Looking at the following expression:

Target * p = dynamic_cast<Target*>(pFarAncestor);

Is there a case where the dynamic conversion type could differ from the left value (p in this case) type? There's a reason, in other words, for explicit all the times the type of the destination variable?

I wonder why compilers do not accept a contracted form like:

Target * p = dynamic_cast<>(pFarAncestor);

or even

Target * p = dynamic_cast(pFarAncestor); // ok this seems a function call indeed

Solution

  • The auto keyword has mainly been introduced for this reason:

    auto p = dynamic_cast<Target*>(pFarAncestor);
    

    If you really want to avoid repeating the type on the right side of the expression, you could use decltype, it is a little bit more verbose though:

    Target * p = dynamic_cast<decltype(p)>(pFarAncestor);
    

    But you obviously have to write the type at least once somewhere.