Compare C++ cast operatorsOld-style casting, unsafe
- (typename)expression
- typename(expression)
New cast operators, varies
- dynamic_cast<type>(expression)
- const_cast<type>(expression)
- static_cast<type>(expression)
- reinterpret_cast<type>(expression)
dynamic_castCode:dynamic_cast<T>(expression)
- Used only on pointer or reference types
- Can be used for up-cast or down-cast (see also
Run Time Type Information RTTI)
- Only for polymorphic types with virtual-functions as these objects have the information about the type: the virtual function table
- Returns null if the cast is unsuccessful
const_castCode:const_cast<T>(expression)
- Is used to remove or add const-ness
- Usually, you should design your variables or methods such that you won’t have to use const_cast
- Failure causes compiler errors
static_cast- Works where implicit conversion exists
- standard or user-defined conversion
- up-casts
- Safer than (typename)expression or typename(expression)
- e.g. won’t cast int* to float*
- Failure causes a compiler error
- No dynamic checking is done!
reinterpret_cast
- Circumvents the type checking of C++; Very dangerous
- Very implementation-dependent
- Rarely used