Static_Cast Operator - Type Casting
How is static_cast operator in C++?
Explanation
Static_Cast operator is used to convert a given expression to the specified type. It is used convert base class pointers to the derived class as well as vice versa. This is type casting in C++.
Example :
#include <iostream.h> using namespace std; int main() { int a = 31; int b = 3; float x = a/b; float y = static_cast<float>(a)/b; cout << "Output without static_cast = " << x << endl; cout << "Output with static_cast = " << y << endl; return 0; }
|
Result :
Output without static_cast = 10
Output with static_cast = 10.3333
In the above type casting example, using the static_cast to an integer as "float" returns a float value.