The static_cast keyword can be used for any normal conversion between types. Conversions that rely on static (compile-time) type information. This includes any casts between numeric types, casts of pointers and references up the hierarchy, conversions with unary constructor, and conversions with conversion operator. For conversions between numeric types no runtime checks are performed if the current content fits the new type. Conversion with unary constructor will be performed even if it is declared as explicit.
TYPE static_cast<TYPE> (object);
It can also cast pointers or references down and across the hierarchy as long as such conversion is available and unambiguous. For example, it can cast
void* to the appropriate pointer type or vice-versa. No runtime checks are performed.
BaseClass* a = new DerivedClass(); static_cast<DerivedClass*>(a)->derivedClassMethod();
- Common usage of type casting
Performing arithmetical operations with varying types of data type without an explicit cast means that the compiler has to perform an implicit cast to ensure that the values it uses in the calculation are of the same type. Usually, this means that the compiler will convert all of the values to the type of the value with the highest precision.
The following is an integer division and so a value of 2 is returned.
float a = 5 / 2;
To get the intended behavior, you would either need to cast one or both of the constants to a float.
float a = static_cast<float>(5) / static_cast<float>(2);
Or, you would have to define one or both of the constants as a float.
float a = 5f / 2f;