An in depth summary of four C++ casts
- 2020-04-01 23:36:02
- OfStack
Four new casts are provided in c++ : const_cast, dynamic_cast, reinterpret_cast, and static_cast.
Each of these four conversion types is suitable for a specific purpose:
Const_cast is generally used to force an object to be unconstant. It is the only C++ style forced transformation that can do this.
Dynamic_cast is primarily used to perform a "safe down transition," that is, to determine whether an object is a specific type in an inheritance scheme. It is the only one that cannot perform forced transitions with old style syntax.
reinterpret_cast Is intended for the underlying transformation, resulting in the result of the implementation, for example, converting a pointer to an integer. Such casts are rare outside the underlying code.
static_cast Can be used to force implicit conversions, such as non-const object to const object, int to double, etc. It can also be used for the reverse of many such conversions, such as: void* pointer to a typed pointer, base pointer to a derived class pointer, but it cannot say a const to a non-const, which is closest to a c-style conversion.
Each of these four conversion types is suitable for a specific purpose:
Const_cast is generally used to force an object to be unconstant. It is the only C++ style forced transformation that can do this.
Dynamic_cast is primarily used to perform a "safe down transition," that is, to determine whether an object is a specific type in an inheritance scheme. It is the only one that cannot perform forced transitions with old style syntax.
reinterpret_cast Is intended for the underlying transformation, resulting in the result of the implementation, for example, converting a pointer to an integer. Such casts are rare outside the underlying code.
static_cast Can be used to force implicit conversions, such as non-const object to const object, int to double, etc. It can also be used for the reverse of many such conversions, such as: void* pointer to a typed pointer, base pointer to a derived class pointer, but it cannot say a const to a non-const, which is closest to a c-style conversion.