C++ Cast Operators
A cast operator is a special operator that converts one data type to another. A cast operator is a unary operator, and its precedence is the same as other unary operators.
Most C++ compilers support most common cast operators:
(type) expression
where type is the converted data type. The following lists several other cast operators supported by C++:
-
const_cast
(expr): The const_cast 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 conversion is mainly used to manipulate the const attribute of the passed object—adding the const attribute or removing it. -
dynamic_cast
(expr): dynamic_cast performs the conversion at runtime and verifies its validity. If the conversion is not performed, the conversion fails and the expression expr is evaluated as null. When dynamic_cast performs a dynamic conversion, type must be a pointer to a class, a reference to a class, or void*; if type is a class pointer type, then expr must also be a pointer; if type is a reference, then expr must also be a reference. -
reinterpret_cast
(expr): The reinterpret_cast operator changes a pointer of one type to a pointer of another type. It can convert a pointer to an integer, or an integer to a pointer. -
static_cast
(expr): The static_cast operator performs non-dynamic conversion, with no runtime class checking to guarantee conversion safety. For example, it can be used to convert a base class pointer to a derived class pointer.
All the cast operators above are used when working with classes and objects. Now, look at the following example to understand how to use a simple cast operator in C++. Copy and paste the C++ program below into a test.cpp file, then compile and run it.
Example
#include
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 code above 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
C++ Operators