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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: C++
Expertise: All
May 20, 1999

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Perform Safe Downcasts

A downcast is a cast from a base to a derived object. Before the introduction of RTTI to the language, downcasts were regarded as bad programming practice--they were unsafe and some even considered the reliance on the dynamic type of an object to be a violation of object-oriented principles. You can perform safe downcasts from a virtual base to its derived object using dynamic_cast.
 
struct V
{
  virtual ~V (){} //ensure polymorphism
};
struct A: virtual V {};
struct B: virtual V {};
struct D: A, B {};

#include <iostream>
using namespace std;
int main()
{
 V *pv = new D;
 A* pa = dynamic_cast<A*> (pv); // downcast
 cout<< "pv: "<< pv << " pa: " << pa <<endl;  // pv and pa have different addresses
 return 0;
}
V is a virtual base for classes A and B. D is multiply-inherited from A and B. Inside main(), pv is declared as a "pointer to V" and its dynamic type is "pointer to D". The dynamic type of pv is needed in order to properly downcast it to a pointer to A. Using a static_cast<> in this case would be rejected by the compiler. As the output of the program shows, pv and pa indeed point to different memory addresses.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date