Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Intermediate
Dec 9, 1998

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
}
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date