4

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
Community
  • 1
  • 1
cppcoder
  • 22,227
  • 6
  • 56
  • 81

4 Answers4

5

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); 
ltjax
  • 15,837
  • 3
  • 39
  • 62
3

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.

RoundPi
  • 5,819
  • 7
  • 49
  • 75
1

From wikipedia:

Unlike an ordinary C-style typecast, a type safety check is performed at runtime, and if the types are not compatible, an exception will be thrown (when dealing with references) or a null pointer will be returned (when dealing with pointers).

http://en.wikipedia.org/wiki/Dynamic_cast

azat
  • 3,545
  • 1
  • 28
  • 30
  • 1
    That's not strictly true. When casting from a derived to a base, as he's doing, the compiler will almost certainly treat a `dynamic_cast` and a `static_cast` identically. The only time a runtime check will occur (and the only time `dynamic_cast` can fail at runtime) is when casting in the opposite direction, from `Base*` to a derived. – James Kanze Jul 28 '11 at 10:42
1

First one is an explicit conversion which is a static_cast. For the difference, you can refer to : http://www.cplusplus.com/doc/tutorial/typecasting/

lwg643
  • 121
  • 2