1.
Introduction
2.
What are Casting Operators?
3.
Syntax of Casting Operators
4.
Implicit Casting Operators
5.
Explicit Casting Operators
6.
Types of Casting Operators
6.1.
Static Casting Operators
6.1.1.
Sample Code
6.2.
Dynamic Casting Operator
6.2.1.

6.2.2.
Sample Code:
6.3.
Const Casting Operator
6.3.1.
Sample Code:
6.4.
Reinterpret Cast Operator
6.4.1.
Sample Code:
7.
7.1.
When should a type cast be used?
7.2.
Does type casting affect the data?
7.3.
Can you cast variables among classes?
7.4.
When do you need to use type-conversions?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

# Casting Operators

Tashmit
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

## Introduction

You might have come across those coding questions in which you have to add two numbers where one is stored as a string, and the other is stored as an integer value. Now the question is, how would the compiler know that a='21' is actually an integer value, and you cannot just add 5 to it. Therefore, casting operators are there for our rescue.

Also, see Literals in C, Fibonacci Series in C++

## What are Casting Operators?

Casting Operators are unary operators used to convert one variable's data type to another. If one variable is stored as a string and the other as an integer, we can still do the required mathematical operations without getting any error from the compiler.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

## Syntax of Casting Operators

``(new_return_type)variable_name``

Let us understand this with a sample code:

``````#include <iostream>
int main()
{
float num = 456.21;
int x;
x = (int)num;
std::cout<<"\nBefore Casting:"<<num<<std::endl;
std::cout<<"\nAfter casting"<<x<<std::endl;
return 0;
}``````

Output:

You can try and compile with the help of online c++ compiler.

## Implicit Casting Operators

Implicit Casting can automatically convert the data type without any programmer or user intervention. In this case, the compiler converts the data types without losing any information. But, it is only applicable if both the data types are compatible and the changed data type is in a higher order than the original data type.

The order of Casting is,

Sample code:

``````#include <iostream>
int main ()
{
int num = 500;
char ch = 'a';
int result = num + 'a';
std::cout<<"\nExplicit Type Casting"<<std::endl;
std::cout << "\nCasting char data type to integer data type ('a' to 500): " << result <<std::endl;
float val = num + 'A';
std::cout << "\nCasting from integer data type to float type: " << val <<std::endl;
return 0;
} ``````

Output:

In the above code, we can see the integer variable num was added to the char ch. It could happen because "a" has an ASCII integer value of 97; therefore, the compiler automatically typecast the char to integer data type.

In further lines of code, the compiler automatically converted the ASCII integer value of A, i.e., 65, to float data type and printed the result.

## Explicit Casting Operators

Explicit Casting is done by the programmer manually according to their requirements. It is not required to check the order of data types; the coder can upgrade or downgrade the data type according to their own choice.

Sample Code:

``````#include <iostream>
int main ()
{
int num = 1024;
int a = 5;
float ans;
ans = (float)num / a;
std::cout<<"\nImplicit Type Casting"<<std::endl;
std::cout << "Dividing two numbers:" << num / a <<std::endl;
std::cout<<"\nExplicit Type Casting"<<std::endl;
std::cout << "Dividing the two numbers: " << ans <<std::endl;
return 0;
}``````

Output:

In the above example, it can be seen when Implicit Casting was applied, there was some data loss, while during explicit Casting, no data was lost.

## Types of Casting Operators

In C++, according to the program's requirements, casting operators to force one data type to be converted to another data type. There are four types of casting operators:

• Static Casting Operator
• Dynamic Casting Operator
• Const Casting Operator
• Reinterpret Casting Operator

### Static Casting Operators

The static_cast is a method to cast the data types of variables. They are checked at the compile time, and the programmer is solely responsible for ensuring that the change was successful without any data loss.

Syntax:

``static_cast <new_data_type>(variable);``

#### Sample Code

``````#include <iostream>
int main()
{
float f = 16.5;
int a = f;
int b = static_cast<int>(f);
std::cout <<"Number after static casting is :"<< b;
}``````

Output:

In the above sample code, we can see that using the static_cast keyword the float variable f was casted to an integer value.

### Dynamic Casting Operator

The dynamic_cast is a method to convert the data types of variables of a class pointer and references. They are checked at run-time, and it returns a NULL value if the Casting is unsuccessful.

Syntax:

``new_data_type* new_pointer = dynamic_cast<new_data_type>(pointer);``

#### Sample Code:

``````#include<iostream>
using namespace std;
class Class1
{
public:
virtual void print () const
{
cout << "This is from Class 1.\n";
}
};
class Class2
{
public:
virtual void print () const
{
cout << "This is from Class 2.\n";
}
};
class Class3:public Class1, public Class2
{
public:
void print () const
{
cout << "This is from Class 3.\n";
}
};
int main ()
{
Class1 *a = new Class1;
Class2 *b = new Class2;
Class3 *c = new Class3;
a->print ();
b->print ();
c->print ();
b = dynamic_cast < Class2 * >(a); //This cast will be failed
if (b)
b->print ();
else
cout << "No Class 2.\n";
a = c;
a->print (); //Printing from Class3
b = dynamic_cast < Class2 * >(a); //Successfully casting is done
if (b)
b->print ();
else
cout << "No Class 2.\n";
}``````

Output:

In the above code, you can see the implementation of dynamic_cast keyword. The keyword can only be used in inheritance.

### Const Casting Operator

The const_cast is a method to handle the const functioning of the source pointer. We can either set a const pointer to a non-const pointer or remove the const from the const pointer.

Syntax:

``const_cast<data_type>pointer;``

#### Sample Code:

``````#include<iostream>
using namespace std;
int fun(int* ptr)
{
return (*ptr + 100);
}
int main(void)
{
const int num = 500;
const int *ptr = &num;
int *new_ptr = const_cast <int *>(ptr);
cout << fun(new_ptr);
return 0;
}``````

Output:

### Reinterpret Cast Operator

The reinterpret_cast is a method to cast a pointer to another pointer even if the pointer and the data it is pointed towards are the same.

Syntax:

``reinterpret_cast<data_type>pointer;``

#### Sample Code:

``````#include <iostream>
using namespace std;
int main()
{
int* num = new int(100);
char* ch = reinterpret_cast<char*>(num);
cout << *num << endl;
cout << *ch << endl;
cout << num << endl;
cout << ch << endl;
return 0;
}``````

Output:

In the above code, the reinterpret_cast keyword was able to typecast a pointer value to another datatype. This type of casting is used when we have to work with bits.

### When should a type cast be used?

Typecasting is used in computer programming to ensure a function correctly processes variables. When a variable is typecast into a different type, the compiler treats the variable as the new data type.

### Does type casting affect the data?

Sometimes, data is lost when the Casting is done from higher to lower order.

### Can you cast variables among classes?

Yes, we can cast variables among classes with the help of Dynamic Casting Operator.

### When do you need to use type-conversions?

We need to use Casting when the value is stored beyond the highest range, and it does not support that data type. Also, to reduce the memory in use, we apply casting operators.

## Conclusion

In this article, we have extensively discussed the casting operators in C++. We hope that this blog has helped you enhance your knowledge and aspects that you should keep in mind while dealing with the operators in C++; here are the articles on operators. If you want to explore and learn big data, make sure to check out this. Do upvote our blog to help other ninjas grow.

Learning never stops, and to feed your quest to learn and become more skilled, head over to our practice platform Coding Ninjas Studio to practice top problems, you can check SQL problems here,  attempt mock tests, read interview experiences, and you can also check our guided path for the coding interview and much more!

Live masterclass