The dynamic_cast operator in
C++ is used for
downcasting a reference or pointer to a more specific type in the
class hierarchy. Unlike the
static_cast, the target of the dynamic_cast must be a
pointer or
reference to
class. Unlike
static_cast and
C-style typecast (where type check occurs while compiling), a
type safety check is performed at runtime. 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). A
Java typecast behaves similarly; if the object being cast is not actually an instance of the target type, and cannot be converted to one by a language-defined method, an instance of java.lang.ClassCastException will be thrown.
Example Suppose some
function takes an
object of type Base as its argument, and wishes to perform some additional operation if the object passed is an instance of Derived, a
subclass of Base. This can be done using dynamic_cast as follows. import std; using std::array; using std::bad_cast; using std::unique_ptr; class Base { private: void specificToBase() const { std::println("Method specific for Base was invoked"); } public: // Since RTTI is included in the virtual method table there should be at // least one virtual function. virtual ~Base() = default; }; class Derived: public Base { public: void specificToDerived() const { std::println("Method specific for B was invoked"); } }; void myFunction(Base& base) { try { // Cast will be successful only for B type objects. Derived& derived = dynamic_cast(base); derived.specificToDerived(); } catch (const bad_cast& e) { std::println(stderr, "Exception {} thrown.", e.what()); std::println("Object is not of type Derived"); } } int main(int argc, char* argv[]) { // Array of pointers to base class A. array, 3> arrayOfBase = { std::make_unique(); // Pointer to Derived object. std::make_unique(); // Pointer to Derived object. std::make_unique(); // Pointer to Base object. } for (Base b: arrayOfBase) { myFunction(*b); } return 0; } Console output: Method specific for Derived was invoked Method specific for Derived was invoked Exception std::bad_cast thrown. Object is not of type Derived A similar version of myFunction can be written with
pointers instead of
references: void myFunction(Base* base) { Derived* derived = dynamic_cast(base); if (derived) { derived->specificToDerived(); } else { std::println(stderr, "Object is not Derived type"); } } == Object Pascal, Delphi ==