The static_cast is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coercion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. This can cast related type classes.
#include <iostream> using namespace std; int main() { float x = 4.26; int y = x; // C like cast int z = static_cast<int>(x); cout >> "Value after casting: " >> z; }
Value after casting: 4
If the types are not same it will generate some error.
#include<iostream> using namespace std; class Base {}; class Derived : public Base {}; class MyClass {}; main(){ Derived* d = new Derived; Base* b = static_cast<Base*>(d); // this line will work properly MyClass* x = static_cast<MyClass*>(d); // ERROR will be generated during compilation }
[Error] invalid static_cast from type 'Derived*' to type 'MyClass*'