- static_cast can be used to cast between fundamental types.
int i; float f; i = static_cast<int>(f);
- static_cast cannot be used to cast between pointers or references to fundamental types.
int *ip, &ir; float f; ip = static_cast<int*>(&f); // illegal ir = static_cast<int&>(f); // illegal
- static_cast can be used to cast between class types if one of the class types has explicit conversion constructor or type casting operator function. For this case, static_cast is the same as explicit casting using parentheses or implicit casting using assignment.
- static_cast can be used to cast derived class type to base class type (public inheritance only), but cannot be used to cast base class type to derived class type if no defined conversion constructor or casting operator. Think about function arguments and exception catch, which are implicit type casting.
- static_cast can be used to cast between pointers or references to related classes (base and derived, public inheritance only). The compiler won't complain if casting base class pointer to derived class pointer. The overhead of type-safe check by dynamic_cast can be avoided. It's the programmers' responsibility to ensure safe conversions.
- static_cast cannot be used to cast for other cases, including between fundamental types and class types, between pointers or references to fundamental types and class types, or between pointers or references to unrelated classes.
- dynamic_cast can be used to cast pointers or references to related classes only (base and derived, public inheritance only). In other words, dynamic_cast won't work on non-pointer/reference types, or pointer/reference to fundamental types.
- When casting between pointers or references to unrelated classes, dynamic_cast will pass compile, but there will be run-time error.
- dynamic_cast can be always successful if casting derived class to base class (public inheritance only).
- When casting from base class to derived class, dynamic_cast will pass compile only when the base class is polymorphic. But there will be run-time error.
- dynamic_cast cannot be used to cast base class to derived class if the base class is not polymorphic. (compile error)
- reinterpret_cast can be used to cast between any pointer or reference types, even between those to unrelated classes or fundamental types or mix.
int *ip, &ir; float f; ip = reinterpret_cast<int*>(&f); ir = reinterpret_cast<int&>(f);
- When using reinterpret_cast, neither the content pointed nor the pointer type itself is checked, and thus dereferencing it is unsafe.
- reinterpret_cast even works on any kind of inheritance, either public, protected, or private.
- reinterpret_cast can be used to cast between pointer types and integer types.
To demonstrate, I wrote a sample code.
Related Posts:
Type Casting in C++
Type Casting on Classes
Assignment between Class Objects
No comments:
Post a Comment