Wednesday, October 14, 2009

understanding dynamic cast

dynamic_cast is a run-time type conversion operator and it ensures only valid conversion can success. The expression dynamic_cast(src) converts expression src to dest_type if appropriate, fails otherwise. Unlike static_cast, it performs type checking at run-time, so it incurs some performance penalty.
static_cast checks if the conversion is valid at compile time. Given this expression static_cast(src), static_cast knows the declaring type of src, with this information static_cast checks if it can be converted to dest_type. If src is actually referring to another type other than src is declared to be, static_cast still considers src to be of its declaring type. So you might get unexpected behavior at run-time.
dynamic_cast takes the actual type of src into consideration. This is achieved with the help of RTTI (Run-time type information) [http://en.wikipedia.org/wiki/Run-time_type_information] which is only available to polymorphic classes. In other words, classes with at least one virtual function defined or inherited. But why?
There are several reasons. First, it has to be compatible with c. It's clear that RTTI must be saved somewhere for each object. If we store the information in every object itself, the layout of object won't be compatible c object model any more because c++ internally add some new fields. Second, not everyone want to use dynamic_cast in their code. Is it fair for all of them to suffer the increased object size and subsequent performance penalty? So RTTI is designed to be enabled only when necessary.
Polymorphism isn't an available feature in C, and it's the source where programmer want to use dynamic_cast. So it's wisely chosen to hold RTTI. The address of a class's RTTI object is placed in virtual table of the class.


There are two requirements for a dynamic_cast to success. complete and unambiguous.

1. Complete
The src must refer to or contain a complete object of target type. For example, if src refers to an concrete object of base type and you try to cast it to derived type, it will fail.

2. Unambiguous
The src must contain a unambiguous object of target type. Take multiple inheritance for instance, it's necessary to explicitly points out which base class to convert to with scope resolution operator.


Casting in C++: Bringing Safety and Smartness to Your Programs http://www.acm.org/crossroads/xrds3-1/ovp3-1.html

No comments: