Static cast
From Wikipedia, the free encyclopedia
- The title of this article should be static_cast. The initial letter is capitalized and an underscore is substituted or omitted because of technical restrictions.
In C++ type conversion, the static_cast operator changes expressions of one static type to objects and values of another static type.
[edit] Syntax
static_cast<type> (object);
The type parameter must be a data type for which there is a known method for converting object to, whether this be a builtin or through a casting function. It can be a reference or an enumerator.
The static_cast operator can be used for operations such as
- Converting a pointer to a base class to a pointer to a derived class,
- Convert numeric data types such as enums to ints or ints to floats.
However, static_cast conversions are not necessarily safe as no run-time type check is done which can cause casting between incompatible data types, for example pointers. However, this is checked at compile time to prevent casting obviously incompatibles. Also, sometimes static_cast between pointer to base to pointer to derived will produce an erroneous result, because of the object layout model.