What is the usage of static_cast in C++?
In C++, static_cast is an operator used for explicit type conversion, allowing conversion between defined types.
There are several ways to use static_cast:
- Basic data type conversion: it is possible to convert one basic data type into another, such as converting an int to a double.
- Assign the integer value 10 to variable a, then cast it to a double and assign it to variable b.
- Pointer or reference conversion in class hierarchies: base class pointers or references can be converted to derived class pointers or references.
- An object of class Derived is being created and stored in a pointer of type Base. This pointer is then casted to a pointer of type Derived.
- Reverse conversion of implicit conversion: allows for the reverse conversion of types with implicit conversion relationships.
- int a has the value of 10. A void pointer named voidPtr is pointing to the address of a. An integer pointer named intPtr is assigned to the address stored in voidPtr after explicitly casting it to an integer pointer.
- Convert function pointer: A function pointer can be converted to another function pointer type.
- The code declares a function named `function1`, creates a function pointer `funcPtr1` pointing to `function1`, and creates another function pointer `funcPtr2` that points to `funcPtr1` after converting its type.
It is important to note that static_cast does not perform dynamic type checking. Therefore, when converting pointers or references, if the conversion is invalid, it can lead to undefined behavior. To avoid such problems, it is recommended to use dynamic_cast for type checking when converting class hierarchies.