4

Possible Duplicate:
Regular cast vs. static_cast vs. dynamic_cast

I learned how static_cast works by this question. Why is it important to use static_cast instead of reinterpret_cast here?

But if static_cast does knows classes' inheritance-relationship, why does dynamic_cast exist? And when do we must use dynamic_cast?

Community
  • 1
  • 1
Benjamin
  • 10,085
  • 19
  • 80
  • 130
  • I forget the specifics, but note that your `static_cast` example did not involve virtual. `dynamic_cast` is specifically used for virtual downcasting. – Pubby Feb 05 '12 at 16:34
  • @Pubby Yes it is. But even if the example has a virtual method, static_cast works fine, am I misunderstanding? – Benjamin Feb 05 '12 at 16:38
  • 1
    *Any* sort of casting should be a rare event in C++, and a dynamic cast is probably one of the rarest among them, but as with most arcane C++ features, when you need it, you really need it. – Kerrek SB Feb 05 '12 at 16:47
  • 2
    It doesn't have anything to do with virtual methods. You have a Base* pointer to an object of a derived class. And like to access a member of that derived class. Cast required, but how do you know that the cast is valid and that the object *actually* is of the expected derived class type? dynamic_cast<> tells you, RTTI must be enabled. – Hans Passant Feb 05 '12 at 17:03

2 Answers2

2

I'll post a simple example of how they differ:

struct foo { virtual void fun() {} };
struct bar : foo {};
struct qux : foo {};

foo* x = new qux;
bar* y = static_cast<bar*>(x);
bar* z = dynamic_cast<bar*>(x);
std::cout << y; // prints address of casted x
std::cout << z; // prints null as the cast is invalid

If I understand correctly, static_cast only knows the type it's casting to. dynamic_cast on the other hand knows type being cast, along with the type being cast to.

Pubby
  • 51,882
  • 13
  • 139
  • 180
-1

dynamic_cast returns NULL if the cast is impossible if the type is a pointer (throws exception if the type is a reference type). Hence, dynamic_cast can be used to check if an object is of a given type, static_cast cannot (you will simply end up with an invalid value).

Also, in some cases static_cast is not possible, e.g. with multiple inheritance:

class Base {};
class Foo : public Base { ... };
class Bar : public Base { ... };
class FooBar: public virtual Foo, public virtual Bar { ... };

FooBar a;
Foo & foo1 = static_cast<Foo &>(a); // Illegal, wont compile
Foo & foo2 = dynamic_cast<Foo &>(a); // Legal
larsmoa
  • 12,604
  • 8
  • 62
  • 85
  • This is incorrect. `static_cast` to virtual base is legal; it's the other way around that's illegal. – Brian Bi Dec 17 '14 at 22:05