dynamic_cast [C++ Reference]
Keywords: keywords,dynamic_cast
Date: 2010-04-28T06:26:27-0700

[[dynamic_cast]]
C++ Reference
Translations of this page?:

- en
- br-pt
- cn
- cz
- de
- es
- fr
- it
- jp
- nl
- pl
- ro
- ru
- sk
- tr
- tw

## dynamic_cast

Syntax:

        TYPE& dynamic_cast<TYPE&> (object);
        TYPE* dynamic_cast<TYPE*> (object);

The dynamic_cast keyword casts a datum 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 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<B*> (&a);  // NULL, because 'a' is not a 'B'
        B* b2 = dynamic_cast<B*> (ap);  // 'b'
        C* c = dynamic_cast<C*> (ap);   // NULL.

        A& ar = dynamic_cast<A&> (*ap); // Ok.
        B& br = dynamic_cast<B&> (*ap); // Ok.
        C& cr = dynamic_cast<C&> (*ap); // std::bad_cast
      }

Related Topics: const_cast, reinterpret_cast, static_cast, A comparison of the C++ casting operators

Edit this page • Old revisions
• • • Login • Index • Recent changes • RSS • cc •