C++ Casting Operators
Casting operators are special operators that convert one data type into another. Casting operators are unary operators with the same precedence as other unary operators.
Most C++ compilers support the majority of common casting operators:
(type) expression
where type
is the target data type. Below are other casting operators supported by C++:
-
constcast<type> (expr): The constcast operator is used to modify the const/volatile attributes of a type. Except for the const or volatile attribute, the target type must be the same as the source type. This type of cast is primarily used to manipulate the const attribute of an object, either adding or removing it.
-
dynamic_cast<type> (expr): The dynamic_cast performs a runtime conversion and verifies its validity. If the conversion fails, the expression expr
is evaluated to null. The dynamic_cast requires type
to be a pointer to a class, a reference to a class, or void*, and expr
must match the type of type
.
-
reinterpretcast<type> (expr): The reinterpretcast operator converts a pointer to another type of pointer. It can also convert a pointer to an integer or an integer to a pointer.
-
staticcast<type> (expr): The staticcast operator performs a non-dynamic conversion without runtime class checks to ensure the safety of the conversion. For example, it can be used to convert a base class pointer to a derived class pointer.
All these casting operators are used when working with classes and objects. Below is an example to understand how a simple casting operator is used in C++. Copy and paste the following C++ program into a file named test.cpp
, compile, and run the program.
#include <iostream>
using namespace std;
int main()
{
double a = 21.09399;
float b = 10.20;
int c ;
c = (int) a;
cout << "Line 1 - Value of (int)a is :" << c << endl ;
c = (int) b;
cout << "Line 2 - Value of (int)b is :" << c << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Line 1 - Value of (int)a is :21
Line 2 - Value of (int)b is :10