Dynamic Cast

The preferred method of downcasting (converting an expression of type Base * or Base & to Derived * or Derived &) in CeePlusPlus with RunTimeTypeInformation turned on. Unlike the raw CeeLanguage cast operator (which causes UndefinedBehavior if the cast fails), DynamicCast will do something useful (return the NullPointer or throw an exception) if the pointed-to object is not of the indicated type (or a subtype). Also adjusts the pointer correctly in the case of MultipleInheritance.

Can also be used for MultipleInheritance crosscasting (converting from type T1 to type T2, where neither type is a subtype of the other) if T1 and T2 derive from a common VirtualBaseClass?. Crosscasting only works in the presence of MultipleInheritance; as for the cast to succeed there must be a type that is a subtype of both T1 and T2. In languages without MI, or in situations where MI is not allowed, crosscasts always fail (and are often called StupidCast?s). To do so, first upcast to the common base type (you can use static_cast for this) then use dynamic_cast to get to T2.

Remember to check the return value if you use the pointer version; deferencing NULL in C++ causes UndefinedBehavior. (It may cause an exception; but the project I'm working on now (an embedded system) does not trap reads/writes to NULL due to CPU/OS limitations.... *@#$@ VxWorks)

A common idiom in C++ is

 void foo(From *asFrom) {
if (To *asTo = dynamic_cast<To *>(asFrom)) {
// do something
}
 }

This will cast "asFrom" of type "pointer to From" to type "pointer to To" and store the result in asTo. The if block is only executed if the cast succeeds (asTo is not zero). asTo will go out of scope when the cast failed or when the if block is left.

The idiom does not work with references, since references cannot be NULL. A failed dynamic_cast on a reference will result in a std::bad_cast exception.


For comparison, this is the equivalent Java idiom:

 void foo(From asFrom) {
     if (asFrom instanceof To) {
         To asTo = (To)asFrom;
         // do something
     }
 }


CategoryCpp


EditText of this page (last edited October 16, 2010) or FindPage with title or text search