The operator dynamic_cast<> comes in two flavors: one uses pointers and the other uses references. Accordingly, dynamic_cast<> returns a pointer or a reference of the desired type when it succeeds. When dynamic_cast<> cannot perform the cast, it returns a NULL pointer, or in case of a reference, it throws a std::bad_cast exception:
void f(Shape & shape) { // A pointer dynamic_cast example: Circle * p = dynamic_cast < Circle *> (&shape); // test whether shape's dynamic type is Circle if ( p ) { p->fillArea (); } // successful cast; use the resultant pointer else {} // shape is of a different type than Circle }
You should always place a reference dynamic_cast<> within a try-block and include a suitable catch-statement:
void f(Shape & shape) { // A reference dynamic_cast example: try { /* attempt to downcast shape */ Circle& ref = dynamic_cast < Circle &> (shape); // reference version of dynamic_cast<> ref.fillArea(); //successful cast; use the resultant object } catch (std:bad_cast& bc) { }// shape is not a Circle}