Why does dynamic_cast exist?

1k Views Asked by At

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?

2

There are 2 best solutions below

1
On

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.

1
On

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