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 using namespace std;int main(){ V *pv = new D; A* pa = dynamic_cast (pv); // downcast cout<< "pv: "<< pv << " pa: " << pa <

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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: