static_cast in C++ | Type Casting operators

A Cast operator is an unary operator which forces one data type to be converted into another data type.
C++ supports four types of casting:

1. Static Cast
2. Dynamic Cast
3. Const Cast
4. Reinterpret Cast

Static Cast: This is the simplest type of cast which can be used. It is a compile time cast.It does things like implicit conversions between types (such as int to float, or pointer to void*), and it can also call explicit conversion functions (or implicit ones).
For e.g.



filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
int main()
{
    float f = 3.5;
    int a = f; // this is how you do in C
    int b = static_cast<int>(f);
    cout << b;
}

chevron_right


Output:

3

Now let’s make a few changes in the code.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
int main()
{
    int a = 10;
    char c = 'a';
  
    // pass at compile time, may fail at run time
    int* q = (int*)&c; 
    int* p = static_cast<int*>(&c);
    return 0;
}

chevron_right


If you compile the code, you will get an error:

[Error] invalid static_cast from type 'char*' to type 'int*'

This means that even if you think you can some how typecast a particular object int another but its illegal, static_cast will not allow you to do this.

Lets take another example of converting object to and from a class.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
#include <string>
using namespace std;
class Int {
    int x;
  
public:
    Int(int x_in = 0)
        : x{ x_in }
    {
        cout << "Conversion Ctor called" << endl;
    }
    operator string()
    {
        cout << "Conversion Operator" << endl;
        return to_string(x);
    }
};
int main()
{
    Int obj(3);
    string str = obj;
    obj = 20;
    string str2 = static_cast<string>(obj);
    obj = static_cast<Int>(30);
    return 0;
}

chevron_right


Run the above code:

Conversion Ctor called
Conversion Operator
Conversion Ctor called
Conversion Operator
Conversion Ctor called

Lets the try to understand the above output:

  1. When obj is created then constructor is called which in our case is also a Conversion Constructor(For C++14 rules are bit changed).
  2. When you create str out of obj, compiler will not thrown an error as we have defined the Conversion operator.
  3. When you make obj=20, you are actually calling the conversion constructor.
  4. When you make str2 out of static_cast, it is quite similar to string str=obj;, but with a tight type checking.
  5. When you write obj=static_cast<Int>(30), you are converting 30 into Int using static_cast.

Lets take example which involves Inheritance.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
class Base {
};
class Derived : public Base {
};
int main()
{
    Derived d1;
    Base* b1 = (Base*)(&d1); // allowed
    Base* b2 = static_cast<Base*>(&d1);
  
    return 0;
}

chevron_right


The above code will compile without any error.

  1. We took address of d1 and explicitly casted it into Base and stored it in b1.
  2. We took address of d1 and used static_cast to cast it into Base and stored it in b2.

As we know static_cast performs a tight type checking, let’s the changed code slightly to see it:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
class Base {
};
class Derived : private Base { // Inherited private/protected not public
};
int main()
{
    Derived d1;
    Base* b1 = (Base*)(&d1); // allowed
    Base* b2 = static_cast<Base*>(&d1);
    return 0;
}

chevron_right


Try to compile the above code, What do you see?? Compilation Error!!!!!!!

[Error] 'Base' is an inaccessible base of 'Derived'

The above code will not compile even if you inherit as protected. So to use static_cast, inherit it as public.

Use static_cast to cast ‘to and from’ void pointer.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
int main()
{
    int i = 10;
    void* v = static_cast<void*>(&i);
    int* ip = static_cast<int*>(v);
    return 0;
}

chevron_right




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


5


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.