static_cast checks if the conversion is valid at compile time. Given this expression static_cast
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/
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/
No comments:
Post a Comment