The static_cast operator (C++ only)

The static_cast operator converts a given expression to a specified type.

Read syntax diagramSkip visual syntax diagramstatic_cast operator syntax
 
>>-static_cast--<--Type-->--(--expression--)-------------------><
 

The following is an example of the static_cast operator.

#include <iostream>
using namespace std;

int main() {
  int j = 41;
  int v = 4;
  float m = j/v;
  float d = static_cast<float>(j)/v;
  cout << "m = " << m << endl;
  cout << "d = " << d << endl;
}

The following is the output of the above example:

m = 10
d = 10.25

In this example, m = j/v; produces an answer of type int because both j and v are integers. Conversely, d = static_cast<float>(j)/v; produces an answer of type float. The static_cast operator converts variable j to a type float. This allows the compiler to generate a division with an answer of type float. All static_cast operators resolve at compile time and do not remove any const or volatile modifiers.

Applying the static_cast operator to a null pointer will convert it to a null pointer value of the target type.

You can explicitly convert a pointer of a type A to a pointer of a type B if A is a base class of B. If A is not a base class of B, a compiler error will result.

You may cast an lvalue of a type A to a type B& if the following are true:

The result is an lvalue of type B.

A pointer to member type can be explicitly converted into a different pointer to member type if both types are pointers to members of the same class. This form of explicit conversion may also take place if the pointer to member types are from separate classes, however one of the class types must be derived from the other.

Related information



[ Top of Page | Previous Page | Next Page | Contents | Index ]