dynamic_cast

From Wikipedia, the free encyclopedia

In the C++ programming language, the dynamic_cast operator is a part of the run-time type information (RTTI) system that performs a typecast. However, unlike an ordinary C-style typecast, a type safety check is incurred at runtime, and it will either throw an exception (when dealing with references) or return a null pointer (when dealing with pointers) if the types are not compatible. Thus, dynamic_cast behaves more like a typecast in a programming language such as Java, rather than the C-style casting which performs no runtime check.

[edit] 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 actually an instance of B, a subclass of A. This can be accomplished using dynamic_cast as follows.

#include <typeinfo> // For std::bad_cast
#include <iostream> // For std::cout, 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 (std::bad_cast e)
        {
                std::cout << "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::cout << "This object is not of type B" << std::endl;
}

[edit] External links

Languages