Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is dynamic_cast required? [duplicate]

Possible Duplicate:
dynamic_cast in c++

What is the difference between these two ways of assigning a derived class to a base class pointer?

Derived d1;
Base *b1 = &d1 

Derived d2;
Base *b2 = dynamic_cast<Base*> &d2
like image 456
cppcoder Avatar asked Jan 20 '23 02:01

cppcoder


2 Answers

It's not required for either of your cases, since both casts cannot possibly fail. Casts from derived to base classes are always valid and don't require a cast.

However, casts from base-class pointers (or references) to derived-class pointer (or references) can fail. It fails if the actual instance isn't of the class it is being cast to. In such a case, dynamic_cast is appropriate:

Derived d1;
Base* b = &d1; // This cast is implicit

// But this one might fail and does require a dynamic cast
Derived* d2 = dynamic_cast<Derived*> (b); // d2 == &d1

OtherDerived d3; // Now this also derives from Base, but not from Derived
b = &d3; // This is implicit again

// This isn't actually a Derived instance now, so d3 will be NULL
Derived* d3 = dynamic_cast<Derived*> (b); 
like image 124
ltjax Avatar answered Feb 01 '23 14:02

ltjax


dynamic_cast can be used for "down cast" and "cross cast" in case of multiple inheritance.

Some valid dynamic_cast example can be found in the link below:

http://msdn.microsoft.com/en-us/library/cby9kycs%28v=vs.71%29.aspx

But dyanmic_cast should not be used frequently, you should aways try to used good design to avoid using dynamic_cast, instead, polymorphism should work for u instead of dynamic_cast.

like image 37
RoundPi Avatar answered Feb 01 '23 16:02

RoundPi