static_cast in C++


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.

Example

#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;
}

Output

Value after casting: 4

If the types are not same it will generate some error.

Example

#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
}

Output

[Error] invalid static_cast from type 'Derived*' to type 'MyClass*'

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements