Latest web development tutorials

C ++ cast operator

C ++ operator C ++ operator

The cast operator is a special operator, which converts the data type to another data type. The cast operator is a unary operator, its priorities and other unary operators the same.

Most C ++ compilers support most common cast operator:

(type) expression 

Here, type is the data type after the conversion. Here are several other cast operator C ++ support:

  • const_cast <type> (expr): const_cast operator is used to modify the type of const / volatile property.In addition to const or volatile attributes, the target must be the same type as the source type. This type of conversion is mainly used to transfer operations const object attributes, you can add const attributes to be removed const attribute.

  • dynamic_cast <type> (expr): dynamic_cast executed at run time to convert, verify the validity of the conversion.If the conversion is not executed, the conversion failed, the expression expr is determined to be null. When dynamic_cast perform a dynamic conversion, type must be a class pointer or reference type void *, if the type is a class pointer type, then expr must be a pointer, if the type is a reference that expr must also be a reference.

  • reinterpret_cast <type> (expr): reinterpret_cast operator to a pointer to some other type of pointer.It can be a pointer to an integer, you can put an integer into a pointer.

  • static_cast <type> (expr): static_cast operator performs non-dynamic conversion, class checks to ensure the safety of the conversion is not running.For example, it can be used to convert a base class pointer to a derived class pointer.

All of the above cast operator in the use of classes and objects will be used. Now, consider the following examples to understand how to use C ++, a simple cast operator. Copy and paste the following C ++ program to test.cpp file, compile and run the program.

#include <iostream>
using namespace std;
 
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 ++ operator C ++ operator