- dynamic_cast
-
In the C++ programming language, the
dynamic_cast
operator is a part of the run-time type information (RTTI) system that performs a typecast. 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). In this regard,dynamic_cast
behaves like a Java typecast.Example code
Suppose some function takes an object of type
A
as its argument, and wishes to perform some additional operation if the object passed is an instance ofB
, a subclass ofA
. This can be accomplished usingdynamic_cast
as follows.#include <typeinfo> // For std::bad_cast #include <iostream> // For std::cerr, etc. class A { public: // Since RTTI is included in the virtual method table there should be at least one virtual function. virtual void foo(); // other members... }; class B : public A { public: void methodSpecificToB(); // other members. }; void my_function(A& my_a) { try { B& my_b = dynamic_cast<B&>(my_a); my_b.methodSpecificToB(); } catch (const std::bad_cast& e) { std::cerr << e.what() << std::endl; std::cerr << "This object is not of type B" << std::endl; } }
A similar version of
my_function
can be written with pointers instead of references:void my_function(A* my_a) { B* my_b = dynamic_cast<B*>(my_a); if (my_b != NULL) my_b->methodSpecificToB(); else std::cerr << "This object is not of type B" << std::endl; }
See also
- static_cast
- reinterpret_cast
- const_cast
External links
Categories:
Wikimedia Foundation. 2010.