dynamic_cast

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 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::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


Wikimedia Foundation. 2010.

Игры ⚽ Поможем сделать НИР

Look at other dictionaries:

  • dynamic_cast — Dans le langage de programmation C++, l opérateur dynamic cast est un membre du système de run time type information (RTTI) qui effectue une conversion de type. Cependant, contrairement au cast hérité du langage C, une vérification du type est… …   Wikipédia en Français

  • dynamic_cast — В языке программирования C++, оператор dynamic cast является частью механизма динамической идентификации типа данных, который позволяет выполнять приведение типа данных. В отличие от обычного приведения типа в стиле Си, проверка корректности… …   Википедия

  • Dynamic cast — В языке программирования C++, оператор dynamic cast является частью механизма динамической идентификации типа данных, который позволяет выполнять приведение типа данных. В отличие от обычного приведения типа в стиле Си, проверка корректности… …   Википедия

  • Multiple dispatch — Theories and practice of polymorphism Double dispatch Multiple dispatch Operator overloading Polymorphism in computer science Polymorphism in OOP Subtyping …   Wikipedia

  • 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. However, unlike an ordinary C style typecast, a type safety check is incurred at runtime, and it will… …   Wikipedia

  • Динамическая идентификация типа данных — Не следует путать с динамической типизацией. Динамическая идентификация типа данных (англ. Run time type information, Run time type identification, RTTI)  механизм в некоторых языках программирования, который позволяет определить тип… …   Википедия

  • Run-time type information — In programming, RTTI (Run Time Type Information, or Run Time Type Identification) refers to a C++ system that keeps information about an object s data type in memory at runtime. Run time type information can apply to simple data types, such as… …   Wikipedia

  • Динамическая идентификация типа — данных (англ. Run time Type Information, Run time Type Identification, RTTI)  механизм, реализованный в языках программирования, который позволяет определить тип данных переменной или объекта во время выполнения программы. Содержание 1 Реализация …   Википедия

  • Множественная диспетчеризация — Мультиметод (англ. multimethod) или множественная диспетчеризация (англ. multiple dispatch) это механизм, позволяющий выбрать одну из нескольких функций в зависимости от динамических типов аргументов. Таким образом, в отличие от обычных… …   Википедия

  • Operators in C and C++ — This is a list of operators in the C and C++ programming languages. All the operators listed exist in C++; the fourth column Included in C , dictates whether an operator is also present in C. Note that C does not support operator overloading.… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”