devxlogo

Perform Safe Downcasts

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.

See also  How IoT Tech Will Transform Logistics
devxblackblue

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.

About Our Journalist