Type conversion
Type conversion
A type cast is basically a conversion from one type to another. There are two types of type
conversion:
1. Implicit Type Conversion Also known as ‘automatic type conversion’.
Done by the compiler on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is present. In
such condition type conversion (type promotion) takes place to avoid lose of data.
All the data types of the variables are upgraded to the data type of the variable with
largest data type.
bool -> char -> short int -> int ->
Type casting:
For example, suppose the given data is an integer type, and we want to convert it into float
type. So, we need to manually cast int data to the float type, and this type of casting is
called the Type Casting in C++.
1. int num = 5;
2. float x;
3. x = float(num);
4. x = 5.0
2nd example:
Type Casting is divided into two types: Implicit conversion or Implicit Type Casting and
Explicit Type Conversion or Explicit Type Casting.
1. char - sort int -> int -> unsigned int -> long int -> float -> double -> long double, etc.
Note: Implicit Type Casting should be done from low to higher data types. Otherwise, it affects the
fundamental data type, which may lose precision or data, and the compiler might flash a warning to this
effect.
Let's create an example to demonstrate the casting of one variable to another using the
implicit type casting in C++.
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. short x = 200;
6. int y;
7. y = x;
8. cout << " Implicit Type Casting " << endl;
9. cout << " The value of x: " << x << endl;
10. cout << " The value of y: " << y << endl;
11.
12. int num = 20;
13. char ch = 'a';
14. int res = 20 + 'a';
15. cout << " Type casting char to int data type ('a' to 20): " << res << endl;
16.
17. float val = num + 'A';
18. cout << " Type casting from int data to float type: " << val << endl;
19. return 0;
20. }
Output:
Implicit Type Casting
The value of x: 200
The value of y: 200
Type casting char to int data type ('a' to 20): 117
Type casting from int data to float type: 85
In the above program, we declared a short data type variable x is 200 and an integer
variable y. After that, we assign x value to the y, and then the compiler automatically
converts short data value x to the y, which returns y is 200.
In the next expressions, we declared an int type variable num is 20, and the character type
variable ch is 'a', which is equivalent to an integer value of 97. And then, we add these two
variables to perform the implicit conversion, which returns the result of the expression is
117.
Similarly, in the third expression, we add the integer variable num is 20, and the character
variable ch is 65, and then assign the result to the float variable val. Thus the result of the
expression is automatically converted to the float type by the compiler.
1. (type) expression;
type: It represents the user-defined data that converts the given expression.
expression: It represents the constant value, variable, or an expression whose data type is
converted.
For example, we have a floating pointing number is 4.534, and to convert an integer value,
the statement as:
1. int num;
2. num = (int) 4.534; // cast into int data type
3. cout << num;
When the above statements are executed, the floating-point value will be cast into an
integer data type using the cast () operator. And the float value is assigned to an integer
num that truncates the decimal portion and displays only 4 as the integer value.
Let's create a simple program to cast one type variable into another type using the explicit
type casting in the C++ programming language.
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. // declaration of the variables
6. int a, b;
7. float res;
8. a = 21;
9. b = 5;
10. cout << " Implicit Type Casting: " << endl;
11. cout << " Result: " << a / b << endl; // it loses some information
12.
13. cout << " \n Explicit Type Casting: " << endl;
14. // use cast () operator to convert int data to float
15. res = (float) 21 / 5;
16. cout << " The value of float variable (res): " << res << endl;
17.
18. return 0;
19. }
Output:
In the above program, we take two integer variables, a and b, whose values are 21 and 2.
And then, divide a by b (21/2) that returns a 4 int type value.
In the second expression, we declare a float type variable res that stores the results of a
and b without losing any data using the cast operator in the explicit type cast method.
Program to cast double data into int and float type using the cast operator
Let's consider an example to get the area of the rectangle by casting double data into float
and int type in C++ programming.
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. // declaration of the variables
6. double l, b;
7. int area;
8.
9. // convert double data type to int type
10. cout << " The length of the rectangle is: " << endl;
11. cin >> l;
12. cout << " The breadth of the rectangle is: " << endl;
13. cin >> b;
14. area = (int) l * b; // cast into int type
15. cout << " The area of the rectangle is: " << area << endl;
16.
17. float res;
18. // convert double data type to float type
19. cout << " \n \n The length of the rectangle is: " << l << endl;
20. cout << " The breadth of the rectangle is: " << b << endl;
21. res = (float) l * b; // cast into float type
22. cout << " The area of the rectangle is: " << res;
23. return 0;
24. }
Output:
1. Static_cast
2. dynamic_cast
3. const_cast
4. reinterpret_cast
Static Cast:
The static_cast is a simple compile-time cast that converts or cast one data type to another.
It means it does not check the data type at runtime whether the cast performed is valid or
not. Thus the programmer or user has the responsibility to ensure that the conversion was
safe and valid.
The static_cast is capable enough that can perform all the conversions carried out by the
implicit cast. And it also performs the conversions between pointers of classes related to
each other (upcast - > from derived to base class or downcast - > from base to derived
class).
Let's create a simple example to use the static cast of the type casting in C++
programming.
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. // declare a variable
6. double l;
7. l = 2.5 * 3.5 * 4.5;
8. int tot;
9.
10. cout << " Before using the static cast:" << endl;
11. cout << " The value of l = " << l << endl;
12.
13. // use the static_cast to convert the data type
14. tot = static_cast < int > (l);
15. cout << " After using the static cast: " << endl;
16. cout << " The value of tot = " << tot << endl;
17.
18. return 0;
19. }
Output:
Dynamic Cast
The dynamic_cast is a runtime cast operator used to perform conversion of one type
variable to another only on class pointers and references. It means it checks the valid
casting of the variables at the run time, and if the casting fails, it returns a NULL value.
Dynamic casting is based on RTTI (Runtime Type Identification) mechanism.
Let's create a simple program to perform the dynamic_cast in the C++ programming
language.
1. #include <iostream>
2. using namespace std;
3.
4. class parent
5. {
6. public: virtual void print()
7. {
8.
9. }
10. };
11. class derived: public parent
12. {
13.
14. };
15.
16. int main ()
17. {
18. // create an object ptr
19. parent *ptr = new derived;
20. // use the dynamic cast to convert class data
21. derived* d = dynamic_cast <derived*> (ptr);
22.
23. // check whether the dynamic cast is performed or not
24. if ( d != NULL)
25. {
26. cout << " Dynamic casting is done successfully";
27. }
28. else
29. {
30. cout << " Dynamic casting is not done successfully";
31. }
32. }
Output:
The reinterpret_cast type casting is used to cast a pointer to any other type of pointer
whether the given pointer belongs to each other or not. It means it does not check whether
the pointer or the data pointed to by the pointer is the same or not. And it also cast a
pointer to an integer type or vice versa.
Let's write a program to demonstrate the conversion of a pointer using the reinterpret in C+
+ language.
1. #include <iostream>
2. using namespace std;
3.
4. int main ()
5. {
6. // declaration of the pointer variables
7. int *pt = new int (65);
8.
9. // use reinterpre_cast operator to type cast the pointer variables
10. char *ch = reinterpret_cast <char *> (pt);
11.
12. cout << " The value of pt: " << pt << endl;
13. cout << " The value of ch: " << ch << endl;
14.
15. // get value of the defined variable using pointer
16. cout << " The value of *ptr: " << *pt << endl;
17. cout << " The value of *ch: " << *ch << endl;
18. return 0;
19.
20. }
Output:
Const Cast
The const_cast is used to change or manipulate the const behavior of the source pointer. It
means we can perform the const in two ways: setting a const pointer to a non-const pointer
or deleting or removing the const from a const pointer.
Let's write a program to cast a source pointer to a non-cast pointer using the const_cast in
C++.
1. #include <iostream>
2. using namespace std;
3.
4. // define a function
5. int disp(int *pt)
6. {
7. return (*pt * 10);
8. }
9.
10. int main ()
11. {
12. // declare a const variable
13. const int num = 50;
14. const int *pt = # // get the address of num
15.
16. // use const_cast to chnage the constness of the source pointer
17. int *ptr = const_cast <int *> (pt);
18. cout << " The value of ptr cast: " << disp(ptr);
19. return 0;
20.
21. }
Output:
Program to access the hidden value using the scope resolution (::) operator
Program1.cpp
1. #include <iostream>
2. using namespace std;
3. // declare global variable
4. int num = 50;
5. int main ()
6. {
7. // declare local variable
8. int num = 100;
9.
10. // print the value of the variables
11. cout << " The value of the local variable num: " << num;
12.
13. // use scope resolution operator (::) to access the global variable
14. cout << "\n The value of the global variable num: " << ::num;
15. return 0;
16. }
Output