Browse DevX
Sign up for e-mail newsletters from DevX

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.



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