Type Conversion in C++

Video Tutorial
FREE
Explicit Typecasting thumbnail
This video belongs to
C++ Course: Learn the Essentials
14 modules
Certificate

Introduction

The conversion of a variable from one data type to another is called Type Conversion in C++. Type conversion in C++ is most commonly used to perform mathematical and logical operations on two variables with different data types.

Types of Type Conversion

Type conversion is the method of converting one data type to another. There are two types of Type Conversions in C++:

  • Implicit type conversion, and
  • Explicit type conversion

Let's understand each one of them.

Implicit Type Conversion

The Implicit Type Conversion is where the type conversion is done automatically by the compiler. It does not require any effort from the programmer. The C++ compiler has a set of predefined rules. The compiler automatically converts one data type to another based on these rules. Therefore, implicit type conversion is also known as automatic type conversion.

Data Loss During Conversion

When there is more than one data type present in an expression, there is a possibility of data loss because different data types are incompatible. Data loss occurs if a variable converts from a higher data type to a lower data type. To avoid data loss, the compiler automatically converts all the data types to the highest data type present in the expression. This is called promotion. The precedence of different data types is given below.

Data Loss Chart

For example:

Output:

The numbers after the decimal point are lost when a float is converted to int. This is why the value 20.5 was converted to 20 when we tried to store a float value in an int variable.

Similarly, when a signed int is implicitly converted to an unsigned int, the sign of the integer is lost.

Order of Typecast in Implicit Conversion

The following is the correct order of automatic conversion from lower rank of data type to higher rank of data type.

Let us take an example to understand implicit type conversion:

Output:

In the above example, we had three variables of different data types. In line 9, we added an integer variable int_var and a character variable char_var. Because of this, the value 'a' present in char_var implicitly converted to the (int) ASCII value of 'a', i.e., 97. Hence, 50 and 97 were added, and 147 were stored in int_var. Similarly, in line 16, we multiplied an integer and a float. The integer was implicitly converted to a float, and the multiplication operation was performed.

Explicit Type Conversion

Explicit Type Conversions are those conversions that are done by the programmer manually. In other words, explicit conversion allows the programmer to typecast (change) the data type of a variable to another type. Hence, it is also called typecasting. Generally, we use the explicit type conversion if we do not want to follow the implicit type conversion rules.

Explicit type conversion in C++ can be done in two ways:

  1. Conversion using the Assignment Operator
  2. Conversion using the Cast Operator

Let us take a look at each one of them.

Conversion Using the Assignment Operator

Explicit typecasting in c++ is done using the assignment operator is also referred to as a forced casting. This conversion is done by explicitly declaring the required data type in front of the expression. It can be done in two ways:

1. C-style type casting:

This type of casting is usually used in the C programming language. It is also known as cast notation. The syntax for this casting is:

For example:

Output:

In this example, we explicitly converted a char variable into an int. The result is the character 'a' was converted to 97.

2. Function style casting

As the name suggests, we can perform explicit typecasting using function-style notations. It is also known as old C++-style type casting. The syntax for this casting is:

For example:

Output:

In this example, we used the function style casting to convert an int variable to float. This is why after dividing the variable by 2, we got 8.5 as the output. If we had not done that, the output would have been 8.

In the above two examples, we used both the C-style type conversion and the function style casting for explicit type conversion. Both of these perform the same task and can be used interchangeably.

Conversion Using the Cast Operator

Besides using the assignment operator, we can also use the cast operator for typecasting. The cast operator forces the conversion of one data type to another. It is a type of unary operator.

Types of Casting in C++

There are 4 types of Casting in C++ programming language. These are:

  1. Static Cast
  2. Dynamic Cast
  3. Const Cast
  4. Reinterpret Cast
Static Cast

The Static Cast is the simplest among all four types of Casting in C++. The static cast can perform all the conversions that are done implicitly. The typecasting using this is done at compile time. This means that no checks are made at the run-time to ensure that the cast performed is valid. Hence, the programmer must ensure the conversion is valid using the static cast.

The Static cast can perform conversions between the pointers of classes related to each other. It can perform upcast (conversion from a derived class to a base class) operations and downcast (conversion from a base class to a derived class) operations.

The syntax for the static cast is:

Let us understand the static cast with an example:

Output:

As we can see, after using the static_cast, double was converted to int. So, the double value 20.35 became an integer 20.

While using the static cast, we must ensure that the datatype being typecasted must be compatible with the new data type. Otherwise, we will get an error.

For example:

Output:

In the above example, we tried to convert char* to int*. Because this operation is invalid (because char takes 1 byte of memory while int takes 2 or 4 bytes), the static cast does not allow this operation and generates an error.

Dynamic Cast

The dynamic cast can only be used with pointers and references to classes (or void*). It is a run-time cast and is used to check the validity of a cast. The expression returns a NULL value if the cast fails. This cast can only be used when we typecast from a parent class to a derived class.

The dynamic cast uses the Run-Time Type Identification (RTTI) mechanism to make all information about the data type of an object available at the run-time. The information is available only for classes with at least one virtual function.

The syntax for the dynamic cast is:

Let us understand the dynamic cast with an example:

Output:

In the above example, we defined two classes - Base and Derived. The class Base contains a virtual function, and the class Derived inherits the class Base. We created a Base class pointer inside the main function, pointing toward a derived class object. Then, we performed dynamic_cast on this pointer to cast it to the Derived class pointer. Because the Base class contains a virtual function (The base class is polymorphic), the dynamic_cast is done successfully.

Const Cast

The Const Cast is used to change an object's constant value or to remove the constant nature of any object. Const cast is generally used in programs with one or more objects with some constant value(s) that need to be changed at some point in the program.

For a const cast operation to be successful, the pointer and the source being cast should be of the same data type.

The syntax for const cast is:

Let us understand the const cast with an example:

Output:

In the above example, the constant pointer ptr1 points to the constant variable var1. We declared another pointer, ptr2, to convert the data type const int* into int* using the const_cast operator. Had we not used const_cast, we would have got an error. Now, because ptr2 contains the address stored in ptr1, we could change the value of the constant pointer ptr1 using the other pointer ptr2.

Reinterpret Cast

The Reinterpret Cast is used to convert one pointer type to another, regardless of whether the classes are related. It does not check whether the pointer type and data pointed out by the pointer are the same. That is why reinterpreting cast should not be used unless required.

Reinterpret cast is mainly used to work with bits. It does not return any value. It directly changes the pointer type. If reinterpret cast is used on boolean values, the boolean values are converted to integers - 0 for false and 1 for true.

The syntax for reinterpret cast is:

Let us understand the reinterpret cast with an example:

Output:

In the above example, we declared an integer pointer ptr pointing to value 98. We also declared a character pointer ch and cast ptr to it using reinterpret cast. After printing the values, we can observe that *ch prints 'b' as 'b' is the equivalent of 98 in ASCII. The value ch contains 98. Hence, ch also prints the ASCII equivalent of 98, i.e., 'b'.

FAQs

Q: Which type of type conversion is done automatically by the compiler in C++?

A: In C++, implicit type conversion, also known as type coercion, is performed automatically by the compiler to convert between compatible data types when needed, such as promoting smaller data types to larger ones or converting literals.

Q: What is the order of automatic conversion from a lower rank of data type to a higher rank of data type in C++? A: In C++, the order of automatic conversion from a lower rank to a higher rank data type is: bool -> char -> short -> int -> unsigned int -> long -> unsigned long -> float -> double -> long double.

Conclusion

  • Changing the data type of a variable is called type conversion.
  • Type conversion in C++ is of two types - implicit and explicit. Implicit type conversion is done automatically by the compiler, while explicit type conversion is done manually by the programmer.
  • Explicit typecasting in C++ can be done in two ways - by using the assignment operator or the cast operator.
  • There are 4 types of cast operators - static cast, dynamic cast, const cast, and reinterpret cast.