Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Samual Sam

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*'

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.