static_cast

In C++ type conversion, the static_cast operator changes expressions of one static type to objects and values of another static type.

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. All types of conversions that are well-defined and allowed by the compiler are done using static_cast. These include typical castless conversions, narrowing conversions, forcing a conversion from a void*, implicit type conversions and static navigation of class hierarchies.[1]

The static_cast operator can be used for operations such as

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 of base to pointer of derived will produce an erroneous result, because of the object layout model.

See also

References

  1. ^ Thinking in C++. United States of America: Alan Apt. 2000. pp. 857. ISBN 0-13-979809-9.