static_cast conversion

From Cppreference

Jump to: navigation, search

Converts between types when no implicit conversion exists.

Contents

[edit] Syntax

static_cast < new_type > ( expression )

All expressions return an value of type new_type.

[edit] Explanation

All above conversion operators compute the value of expression, convert it to type and return the resulting value. Each conversion can take place only in specific circumstances or the program is ill formed.

Performs one of the following conversions, except when such conversion would cast away constness or volatility.

1. If a temporary object of type type can be declared and initialized with the expression type Temp(expression);, which may involve execution of type's single-argument constructor and implicit conversions of the result of expression, then static_cast<type>(expression) computes and returns the value of that temporary object.

2. If type is a pointer or reference to some class D and the result of expression is a pointer or reference to its non-virtual base B, static_cast performs a downcast. Such static_cast makes no runtime checks to ensure that the object's runtime type is actually D, and may only be used safely if this precondition is guaranteed by other means, such as when implementing static polymorphism.

3. If type is an rvalue reference, static_cast converts the value of expression to xvalue. This type of static_cast is used to implement move semantics in std::move. (C++11 feature)

4. If type is the type void (possibly cv-qualified), static_cast discards the value of expression after evaluating it.

5. If an implicit conversion sequence from type to the type of expression exists that does not include lvalue-to-rvalue, array-to-pointer, function-to-pointer, null pointer, null member pointer, or boolean conversion, then static_cast can perform the inverse of that implicit conversion.

6. If conversion of expression to type is an lvalue-to-rvalue, array-to-pointer, or function-to-pointer conversion, it can be performed explicitly by static_cast.

7. Scoped enumeration type can be converted to an integer or floating-point type. (C++11 feature)

8. Integer, floating-point, or enumeration type can be converted to any enumeration type (the result is unspecified if the value of expression, converted to the enumeration's underlying type, is not one of the target enumeration values)

9. A pointer to member of some class D can be upcast to a pointer to member of its base class B. This static_cast makes no checks to ensure the member actually exists in the runtime type of the pointed-to object.

10. A prvalue of type pointer to void (possibly cv-qualified) can be converted to pointer to any type. Conversion of any pointer to pointer to void and back to pointer to the original (or more cv-qualified) type preserves its original value.

[edit] Keywords

static_cast

[edit] Example

[edit] See also