A static_cast c++ operator is a unary operator that compels the conversion of one data type to another. This is the most basic cast available. The static_cast takes a long time to compile, and it can do implicit type conversions (such as int to float or pointer to void*) as well as call explicit conversion routines (or implicit ones).

Example

#include <iostream>

using namespace std;

int main()

{

            float f = 6.7

            int a = f; // this is how you do in C

            int b = static_cast<int>(f);

            cout << b;

}

Output

Static_cast_in_Cpp_1

Now let’s make some changes in the code and see the output.

#include <iostream>

using namespace std;

int main()

{

            int Z = 10;

            char D = 'Z';

            // pass at compile time, may fail at run time

            int* q = (int*)&c;

            int* p = static_cast<int*>(&c);

            return 0;

}

Output

Static_cast_in_Cpp_2

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

What Are Type Conversions?

There are two types of type conversions in static_cast c++:

  • Implicit Conversions

Implicit conversions are also called automatic type conversions. Without any external trigger from the user, the compiler performs this task on its own. This usually happens when more than one data type is present in an expression. In such a situation, type conversion (type promotion) occurs to avoid data loss.

If the expression has multiple data types, the compiler automatically converts all the variables to the most occured type in the expression. For instance, if an expression has three strings, two integers, and one boolean value, implicit conversion will convert all the parameters to an integer data type.

// An example of implicit conversion

#include<stdio.h>

int main()

{

            int x = 5; // integer x

            char y = 'a'; // character c

            // y implicitly converted to int. ASCII

            // value of 'a' is 97

            x = x + y;          

            // x is implicitly converted to float

            float z = x + 7.0;

            printf("x = %d, z = %f", x, z);

            return 0;

}

Output

Static_cast_in_Cpp_3

  • Explicit Conversion

This is also known as typecasting, and it is a user-defined process. The user can typecast the result to convert it to a certain data type.

Example

// C program to demonstrate explicit typecasting

#include<stdio.h>

int main()

{

double x = 1.0;

// 

int sum = (int)x + 1;

printf("sum = %d", sum);

return 0;

}

Output

Static_cast_in_Cpp_4

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Syntax of Static_cast in C++

For the normal/ordinary type conversion, static_cast c++ is employed. This cast can also be called explicitly and is responsible for implicit type conversion. You should utilize it when converting floats to ints, chars to ints, and so on. This can be used to cast type classes that are related.  

Example of Static_cast

#include <iostream>

using namespace std;

int main() {

  int j = 4;

  int v = 4;

  float m = a/b;

  float d = static_cast<float> (a)/b;

  cout << "m = " << m << endl;

  cout << "d = " << d << endl;

}

Output:

Static_cast_in_Cpp_5

Because both j and v are integers, m = j/v; yields a response of type int in this case. In contrast, d = static_cast(j)/v; returns a float answer. The static_cast c++ operator changes the type of variable j to float. This enables the compiler to construct a division with a float response. All static_cast operators are resolved at compilation time, and no const or volatile modifiers are removed. The static_cast c++ operation casts a null pointer value of the target type to a null pointer value of the target type.

Casting Through Inheritance

  • Upcasting

Upcasting allows us to treat a derived type as the base type. Without an explicit type cast, public inheritance is always available. You can execute upcasting by using the is-a relationship between the base and derived classes.

Example

void play(Shape& s)

{

   s.draw();

   s.move();

   s.shrink();

   ....

}

Circle c;

Triangle t;

Square sq;

play(c);

play(t);

play(sq);

Explanation

The above code was for dealing with shapes. We developed the Shape class from which we derived the Circle, Square, and Triangle classes. After that, we created a member function that communicates with the base class.

We can treat a derived type as if it were its base type by upcasting it. That's how we separate ourselves from the specific type we're working with.

It doesn't state, "If you're a Triangle, do this," "If you're a Circle, do that," or "If you're a Square, do that," and so on. If we develop code that checks for all conceivable Shapes, it would quickly become a jumbled mess, and we will have to rewrite it every time we introduce a new type of Shape. 

  • Downcasting

Downcasting is the process of transforming a base-class pointer (reference) to a derived-class pointer (reference). Without an explicit type cast, downcasting is not permitted. The reason for this limitation is that in most circumstances, the is-a connection is not symmetric. The class member procedures that used these data members wouldn't apply to the base class if a derived class added additional data members.

We created a Child class from a Parent class and added a member function, gotoSchool, as shown in the example (). It's not logical to use the gotoSchool() method on a Parent object.

This conversion is performed using a particular explicit cast in C++ called a dynamic cast. The basic object-oriented rule asserts that objects of a derived class can always be assigned to variables of a base class. Downcasting is the polar opposite of this rule.

One final note on the upcasting:

Dynamic binding is required because implicit upcasting allows a base-class pointer (reference) to refer to a base-class object or a derived-class object. That is why virtual member functions exist.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Static_cast vs. Dynamic_cast in C++

We already know that in C++, we can assign one type of variable to another type of variable. But what if the data types of the two variables aren't the same? Implicit type conversion would occur in this scenario. It is the process of converting one data type to another. In C++, typecasting may or may not be supported implicitly. If it isn't supported, we'll have to resort to using C++'s casting methods, namely:

  • static_cast c++ 
  • const cast 
  • reinterpret_cast 
  • dynamic_cast 
  • Static_cast

The static_cast is the most basic of the casts. Static_cast c++ just does implicit type conversions.

Example

#include<iostream>

using namespace std;

int main()

{

float f = 7.8;

int i,j;

i = f; //

j = static_cast<int>(f);

cout<<i<<"\n"<<j;

}

Output

Static_cast_in_Cpp_6

In this example, the float data type is being converted to an integer value. In essence, lines 7 and 8 are performing the same thing. So, what is the distinction?

If the program fails and we want to see where the implicit cast is being performed, locating line 7 in a large amount of code can be time-consuming. As a result, we use static_cast c++ in this scenario to easily search it.

At compile time, static_cast is used. The program examines whether we can typecast the float type ‘ f ‘ into the integer type ‘ a'.

  • Dynamic_cast

A derived class pointer can be treated as a base class pointer in C++. In C++, this is known as upcasting. In C++, the reverse procedure, known as downcasting, is not permitted. As a result, the dynamic cast is used in C++ to promote safe downcasting. It is always carried out with polymorphic classes that have at least one virtual function.

Example

#include<bits/stdc++.h>

using namespace std;

class base

{

public:

virtual void car()

{

cout<<"base";

}

};

class derived:public base

{

public:

void gun()

{

cout<<"derived";

}

};

int main()

{

base *b = new derived;

derived *d;

d=b; //base class pointer assigned to the derived class pointer

d->gun();

}

Output

Static_cast_in_Cpp_7

If you're eager to gain the skills required to work in a challenging, rewarding, and dynamic IT role - we've got your back! Discover the endless opportunities through this innovative Post Graduate Program in Full Stack Web Development course designed by our partners at Caltech CTME. Enroll today!

Conclusion 

This was a quick guide to help you understand the concept of static_cast in C++. If you want to learn more about static_cast in C++ and other such concepts, you must enroll in the Full Stack Web Development Program by Simplilearn. Enrolling in this program will help you learn modern coding techniques in just a few months and help you secure a rewarding career and several job opportunities. 

You can also check out the SkillUp platform, an initiative by Simplilearn, where you’ll find free online skill-up courses in domains like data science, business analytics, software development, AI, and machine learning. Identify and pursue the course that works best for your specific career goals!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 27 Nov, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449