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.

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several