devxlogo

Two Flavors of dynamic_cast<>

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}

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Five Early Architecture Decisions That Quietly Get Expensive

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.