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

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 // For std::bad_cast
#include // 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(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(my_a);

if (my_b != NULL) my_b->methodSpecificToB(); else std::cout << "This object is not of type B" << std::endl;}

External links

* [http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc05keyword_dynamic_cast.htm dynamic_cast operator at IBM Mac OS X Compilers]
* [http://msdn2.microsoft.com/en-us/library/cby9kycs.aspx dynamic_cast operator at MSDN]


Wikimedia Foundation. 2010.

Игры ⚽ Нужен реферат?

Look at other dictionaries:

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

  • Dynamic loading — is a mechanism by which a computer program can, at run time, load a library (or other binary) into memory, retrieve the addresses of functions and variables contained in the library, execute those functions or access those variables, and unload… …   Wikipedia

  • Dynamic load testing — of piles is a fast and effective method of assessing foundation bearing capacity that requires instrumenting a deep foundation with accelerometers and strain transducers and analyzing data collected by these sensors. The procedure is based on the …   Wikipedia

  • Cast-Nephropathie — Klassifikation nach ICD 10 C90.0+ Plasmozytom (Multiples Myelom) N08.1* Glomeruläre Krankheiten bei Neubildungen Glomeruläre Krankheiten bei Plasmozytom …   Deutsch Wikipedia

  • C dynamic memory allocation — C Standard Library Data types Character classification Strings Mathematics File input/output Date/time Localization …   Wikipedia

  • Operation Cast Lead — Operation Gegossenes Blei Teil von: Nahostkonflikt Karte des Gazastreifens …   Deutsch Wikipedia

  • List of Heroes cast members — This is a list of recurring actors on the US television show Heroes . Every actor credited in two episodes or more is included in the article, which covers episodes 1.01 to 3.04. Main castThis list shows the show s main cast, and the number of… …   Wikipedia

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

  • Comparison of programming languages — Programming language comparisons General comparison Basic syntax Basic instructions Arrays Associative arrays String operations …   Wikipedia

  • Type conversion — This article is about the computer science concept. For the aviation licensing process, see Type conversion (aviation). In computer science, type conversion, typecasting, and coercion refers to different ways of, implicitly or explicitly,… …   Wikipedia

Share the article and excerpts

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