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
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With