Cast Operations |
6 |
![]() |
The emerging C++ standard defines new cast operations that provide finer control over casting than previous cast operations. The dynamic_cast<> operator provides a way to check the actual type of a pointer to a polymorphic class. Otherwise, the new casts all perform a subset of the casts allowed by the classic cast notation. For example, const_cast<int*>v could be written (int*)v. The new casts simply categorize the variety of operations available to express the programmer's intent more clearly and allow the compiler to better check the code.
Reinterpret Cast
The expression reinterpret_cast<T>(v)changes the interpretation of the value of the expression v. It will convert from pointer types to integers and back again, between two unrelated pointers, pointers to members, or pointers to functions. The only guarantee on such casts is that a cast to a new type, followed by a cast back to the original type, will have the original value. It is legal to cast an lvalue of type T1 to type T2& if a pointer of type T1* can be converted to a pointer of type T2* by a reinterpret_cast. reinterpret_cast cannot be used to convert between pointers to two different classes that are related by inheritance (use static_cast or dynamic_cast), nor can it be used to cast away const (use const_cast).
Static Cast
The expression static_cast<T>(v) converts the value of the expression v to that of type T. It can be used for any cast that is performed implicitly on assignment. In addition, any value may be cast to void, and any implicit cast can be reversed if that cast would be legal as an old-style cast. It cannot be used to cast away const.
Dynamic Cast
A pointer or reference to a class can actually point to any class publicly derived from that class. Occasionally, it may be desirable to obtain a pointer to the fully-derived class, or to some other base class for the object. The dynamic cast provides this facility.
class A { public: virtual void f( ); }; class B { public: virtual void g( ); }; class AB : public virtual A, private B { }; |
The following function will succeed.
class AB_B : public AB, public B { }; class AB_B__AB : public AB_B, public AB { }; |
The following function will succeed:
If run-time type information has been disabled, i.e. -features=no%rtti, (See Chapter 5, "RTTI"), the compiler converts dynamic_cast to static_cast and issues a warning.