0% found this document useful (0 votes)
5 views

Type conversion

The document explains type conversion in C++, detailing implicit and explicit type casting. Implicit conversion occurs automatically by the compiler, while explicit conversion requires user intervention using cast operators. It also describes four types of cast operators: static_cast, dynamic_cast, const_cast, and reinterpret_cast, along with examples of their usage.

Uploaded by

divya R K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Type conversion

The document explains type conversion in C++, detailing implicit and explicit type casting. Implicit conversion occurs automatically by the compiler, while explicit conversion requires user intervention using cast operators. It also describes four types of cast operators: static_cast, dynamic_cast, const_cast, and reinterpret_cast, along with examples of their usage.

Uploaded by

divya R K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

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 ->

 unsigned int -> long -> unsigned ->


 long long -> float -> double -> long double


 It is possible for implicit conversions to lose information, signs can be lost (when
signed is implicitly converted to unsigned), and overflow can occur (when long long is
implicitly converted to float).
Example of Type Implicit Conversion:
Output:
x = 107
y = a
z = 108
2. 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:
 Converting by assignment: This is done by explicitly defining the required type in
front of the expression in parenthesis. This can be also considered as forceful casting.
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
Example:
Output:
Sum = 2
 Conversion using Cast operator: A Cast operator is an unary operator which
forces one data type to be converted into another data type.
C++ supports four types of casting:
1. Static Cast
2. Dynamic Cast
3. Const Cast
4. Reinterpret Cast
Example:
Output:
3
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.

Type casting:

Type Casting in C++


This section will discuss the type casting of the variables in the C++ programming
language. Type casting refers to the conversion of one data type to another in a program.
Typecasting can be done in two ways: automatically by the compiler and manually by the
programmer or user. Type Casting is also known as Type Conversion.

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:

1. float num = 5.25;


2. int x;
3. x = int(num);
4. Output: 5

Type Casting is divided into two types: Implicit conversion or Implicit Type Casting and
Explicit Type Conversion or Explicit Type Casting.

Implicit Type Casting or Implicit Type Conversion

o It is known as the automatic type casting.


o It automatically converted from one data type to another without any external
intervention such as programmer or user. It means the compiler automatically
converts one data type to another.
o All data type is automatically upgraded to the largest type without losing any
information.
o It can only apply in a program if both variables are compatible with each other.

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.

Program to use the implicit type casting in C++

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.

Explicit Type Casting or Explicit Type Conversion

o It is also known as the manual type casting in a program.


o It is manually cast by the programmer or user to change from one data type to
another type in a program. It means a user can easily cast one data to another
according to the requirement in a program.
o It does not require checking the compatibility of the variables.
o In this casting, we can upgrade or downgrade the data type of one variable to another
in a program.
o It uses the cast () operator to change the type of a variable.

Syntax of the explicit type casting

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.

Program to demonstrate the use of the explicit type casting in C++

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:

Implicit Type Casting:


Result: 4

Explicit Type Casting:


The value of float variable (res): 4.2

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:

The length of the rectangle is:


57.3456
The breadth of the rectangle is:
12.9874
The area of the rectangle is: 740

The length of the rectangle is: 57.3456


The breadth of the rectangle is: 12.9874
The area of the rectangle is: 744.77

Some different types of the Type Casting


In type cast, there is a cast operator that forces one data type to be converted into another
data type according to the program's needs. C++ has four different types of the cast
operator:

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).

Syntax of the Static Cast

1. static_cast < new_data_type> (expression);

Program to demonstrate the use of the Static Cast

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:

Before using the static cast:


The value of l = 39.375
After using the static cast:
The value of tot = 39

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.

Program to demonstrate the use of the Dynamic Cast in C++

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:

Dynamic casting is done successfully.

Reinterpret Cast Type

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.

Syntax of the reinterpret_cast type

1. reinterpret_cast <type> expression;

Program to use the Reinterpret Cast in C++

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:

The value of pt: 0x5cfed0


The value of ch: A
The value of *ptr: 65
The value of *ch: A

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.

Syntax of the Const Cast type

1. const_cast <type> exp;

Program to use the Const Cast in C++

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:

The value of ptr cast: 500

Scope Resolution Operator in C++


This section will discuss the scope resolution operator and its various uses in the C++
programming language. The scope resolution operator is used to reference the global
variable or member function that is out of scope. Therefore, we use the scope resolution
operator to access the hidden variable or function of a program. The operator is
represented as the double colon (::) symbol.
For example, when the global and local variable or function has the same name in a
program, and when we call the variable, by default it only accesses the inner or local
variable without calling the global variable. In this way, it hides the global variable or
function. To overcome this situation, we use the scope resolution operator to fetch a
program's hidden variable or function.

Uses of the scope resolution Operator

1. It is used to access the hidden variables or member functions of a program.


2. It defines the member function outside of the class using the scope resolution.
3. It is used to access the static variable and static function of a class.
4. The scope resolution operator is used to override function in the Inheritance.

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

The value of the local variable num: 100


The value of the global variable num: 50

You might also like