C++ Cast operator

C++ Operators

Cast operators are special operators that convert one data type to another. Cast operators are unary operators, and their precedence is the same as other unary operators.

Most C++ compilers support most of the common cast operators:

(type) expression 

Here, type is the data type after conversion. The following lists several other cast operators supported by C++:

  • const_cast<type> (expr):The const_cast operator is used to modify the const/volatile attributes of a type. Except for the const or volatile attributes, the target type must be the same as the source type. This type of cast is mainly used to manipulate the const attribute of the passed object; it can add the const attribute or remove the const attribute.

  • dynamic_cast<type> (expr):dynamic_cast performs the conversion at runtime and verifies the validity of the conversion. 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<type> (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 convert an integer to a pointer.

  • static_cast<type> (expr):The static_cast operator performs non-dynamic conversions, with no 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 the casting operators mentioned above are used with classes and objects. Now, look at the following example to understand how to use a simple casting operator in C++. Copy and paste the following C++ program into the test.cpp file, then compile and run the program.

Example

#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 results:

Line 1 - Value of (int)a is :21
Line 2 - Value of (int)b is  :10

C++ Operators

other extensions