=====dynamic_cast=====
Syntax:
T& dynamic_cast (object);
T* dynamic_cast (object);
The ''dynamic_cast'' keyword casts ''object'' from one pointer or reference type to another, performing a runtime check to ensure the validity of the cast.
If you attempt to cast to a pointer type, and that type is not an actual type of the argument object, then the result of the cast will be **NULL**.
If you attempt to cast to a reference type, and that type is not an actual type of the argument object, then the cast will throw a [[/support/rtti/bad_cast|std::bad_cast]] exception.
struct A {
virtual void f() { }
};
struct B : public A { };
struct C { };
void f () {
A a;
B b;
A* ap = &b;
B* b1 = dynamic_cast (&a); // NULL, because 'a' is not a 'B'
B* b2 = dynamic_cast (ap); // 'b'
C* c = dynamic_cast (ap); // NULL.
A& ar = dynamic_cast (*ap); // Ok.
B& br = dynamic_cast (*ap); // Ok.
C& cr = dynamic_cast (*ap); // std::bad_cast
}
If the value of ''object'' is a null pointer, then the result is a null pointer of type ''T''.
Related Topics: [[const_cast]], [[reinterpret_cast]], [[static_cast]], [[casting_comparison]]