Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ Cast Operators

C++ Cast Operators

C++ Operators C++ 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++:

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 C++ Operators