A type cast is basically a conversion from one type to another. There are two types of type conversion:
- Implicit Type Conversion Also known as ‘automatic type conversion’.
Example of Type Implicit Conversion:
#include <iostream>
using namespace std;
int main()
{
int x = 10;
char y = 'a' ;
x = x + y;
float z = x + 1.0;
cout << "x = " << x << endl
<< "y = " << y << endl
<< "z = " << z << endl;
return 0;
}
|
Output:
x = 107
y = a
z = 108
- Explicit Type Conversion: This process is also called type casting and it is user-defined. Here the user can typecast the result to make it of a particular data type.
In C++, it can be done by two ways:
Advantages of Type Conversion:
- This is done to take advantage of certain features of type hierarchies or type representations.
- It helps to compute expressions containing variables of different data types.