Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Type Casting and Type Conversion in C++
2.1.
Implicit Type Conversion
2.2.
C++
2.3.
C++
2.4.
Explicit Conversion
2.4.1.
C-style Type Casting
2.5.
C++
2.5.1.
Function-style Casting
2.6.
C++
3.
Type Conversion Operators
4.
Frequently Asked Questions
4.1.
What is a good use of typecasting?
4.2.
Difference between the Implicit Conversion and Explicit Conversion in C++.
4.3.
How many types of casting operators are present in C++?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Type Casting and Type Conversion in Cpp

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

In general, the act of changing from one form to another is conversion. An example of conversion ( or transformation) is exchanging dollars for euros. In simple words, it’s converting the existing item with the newly desired item.

They are not converting anything because they are not aware of the concept of conversion, which is precisely our discussion today. Now, let’s get started with Type Casting and Type Conversion in C++.

typecasting in c++

Type Casting and Type Conversion in C++

In computer science, type conversion or typecasting refers to changing an entity of one data type into another. An example of typecasting is converting an integer to a string. This compares the two numbers when one is a string and the other an integer. Before moving ahead, let’s understand the difference between Type Casting and Type Conversion in C++.

In Type Casting, a datatype is converted into the desired data type by the programmer using the Casting operator. Whereas, in type conversion, the compiler itself converts the data type into the required data type.

There are two types of Type Conversion in C++:

Type Conversion

Implicit Type Conversion

In Implicit ( or automatic ) type conversion, the compiler converts one data type to another data type. This process doesn’t need any user involvement. In simple words, the compiler is doing the conversion itself. It generally occurs when more than one data type is present in an expression.

Example 1:

int num= 45;   float num2 = 7.8;
int sum = num + num2;    // type of sum is an integer


What will be the value in the sum variable?

  • 52
     

The compiler here automatically converts the floating number into the integer type, i.e., ( 7.8 to 7). 

Example 2:

char a = ‘A’ ;    
int num = 45;
int sum = a + num;


Now, Guess the output?

  • 110
     

As we know, the ASCII value of A is 65. The compiler automatically adds the ASCII value(65)  with num(45). Hence, the output comes as 110.

Type Promotion

Type Promotion

Note:- It is possible to lose information in Implicit conversion as the signs can be lost (when signed is implicitly converted to unsigned), and overflow can occur when a large datatype is transformed into a small byte of data type. ( e.g., long long is implicitly converted to float).

Now, let’s see the C++ example Codes to Illustrate the Implicit Conversion.

  • C++

C++

#include<iostream>
using namespace std;
int main()
{
   float num = 4.5;
   char c = 'a'; //c implicitly converted to int.
                           // ASCII value of 'a' is 97  & then to float => 97.0
                           
   float sum=0.0;
   sum = num + c;
   cout<<"c is = "<<c<<endl;
   cout<<"Sum is "<<sum<<endl;
  
   return 0;
}


Output

c is = a
Sum is 101.5


Explanation:- In the above code, we’ve initialised two variables of type float and char. 

Afterwards, the addition of both variables is being performed. Since the sum variable is of floating type, the c variable implicitly will get converted into the floating value. Here, the compiler itself changes one data type into the destination data type.

Let’s see an example in which we will be encountering Data Loss.

  • C++

C++

#include <iostream>
using namespace std;

int main() {

  int int_num;
  double double_num = 7.88;

  // implicit conversion
  // assigning a double value to an int variable

  int_num = double_num;
 
  cout<<"Integer number = "<<int_num<<endl;
  cout<<"Double number = "<<double_num<<endl;

  return 0;
}


OUTPUT

Integer number = 7
Double number = 7.88

 

Since int cannot have a decimal part, the digits are truncated in the above example after the decimal point. Hence, Loss of data is possible in Implicit Conversion. You can also do a free certification of Basics of C++.

Explicit Conversion

When the user manually changes the data type of one to another, it is known as Explicit Conversion. This type of conversion is also known as Type Casting, where the user’s involvement is present. To understand the typecasting, we need to know about the cast operator. A cast operator is a unary operator which coerces one data type to be conveyed into another.

Further, Six types of Explicit Conversion are

  1. C-style Type Casting
  2. Function style Casting
  3. Static_cast
  4. Const_cast
  5. Dynamic_cast
  6. Reinterpret_cast
Explicit Conversion

C-style Type Casting

As the name suggests, this type of casting is favoured by the C programming language. Cast notation is the other name for C-style casting.

Syntax:-

( new data_type) expression;

For example:

  • C++

C++

#include<iostream>
using namespace std;
int main(){
   int num;
   bool b = false; // false =0 , true = 1
   num = (int)b;  // c-style type casting
   cout<<"num is = "<<num<<endl;
   return 0;
}


Output

num is = 0


In programming, 0 is false, and 1 is true. Since the b (bool) variable holds the false means (0), the num will be assigned with 0.

Now, if we already have Implicit Conversion, then why do we need Explicit Conversion?

Let’s understand with one example:

int a = 3; int b = 2;

float div = a/b;

Result = 1, which is imprecise.

When the explicit type casting is being performed, then the result will be precise.

float = (float) a/b;

Result = 1.5, which is accurate.

This precisely shows us the need for Explicit Conversions.

Function-style Casting

We can also use function notation to convert the data type into another type. It is like a function call where the type to be cast is the function’s name, and the value to be cast behaves like an argument to the function.

Syntax:

data_type ( expression );

Example:

  • C++

C++

#include <iostream>
using namespace std;

int main()
{
   double num_double = 9.87;
   int num_int;
   num_int = int(num_double); // function-type casting
   cout<<"Integer number = "<<num_int;
   return 0;
}


Output

Integer number = 9


Explanation:- In the above code, we have declared the integer variable named num_int. Here, we assigned the value inside the num_double to the num_int variable. We can also perform the same process with the help of C-style Casting, which works exactly like the function style casting irrespective of the syntax. 

Further, you can check out this blog’s part 2 on casting operators to read more about each one of them in detail.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Type Conversion Operators

C++ offers four operators for type conversion in addition to these two type castings. They are referred to as type conversion operators. They are as follows:

  • static_cast: This is the most basic type of cast available. It's a compilation time cast. It can do implicit type conversions (such as int to float or pointer to void*) as well as call explicit conversion routines.
     
  • dynamic_cast: Dynamic cast is a data conversion operator that transfers data from one type to another. Dynamic casting is mostly utilized in C++ for safe downcasting at runtime. There must be one virtual function in the base class to work on dynamic_cast. As it uses this information to determine safe downcasting, dynamic_cast only works on polymorphic base classes.
     
  • const_cast: const_cast is a C++ type-casting operator that removes const qualifier from a variable temporarily, allowing it to be modified; however, it should be used with caution to avoid undefined behavior and ensure proper const correctness in your code.
     
  • reinterpret_cast: reinterpret_cast is a very unique and risky casting operator. It is also recommended to use it with the right data type, i.e. (pointer data type should be the same as original data type). Any pointer can be typecast to any other data type.

Frequently Asked Questions

What is a good use of typecasting?

In C/C++, typecasting is a method of converting a variable's data type to another data type. It comes in handy when it comes to memory management. If you wish to save a value of type int into a variable of type long, we can do so by typecasting int to long.

Difference between the Implicit Conversion and Explicit Conversion in C++.

Implicit conversion is automatically performed by the compiler when differing data types are intermixed in an expression. Whereas, Explicit conversion is a user-defined conversion that forces an expression to be of a specific type.

How many types of casting operators are present in C++?

There are specific four type casting operators:- static_cast, dynamic_cast, const_cast, and reinterpret_cast.

Conclusion

To summarise, we’ve discussed the overview on Type Casting and Type Conversion in C++. Type Casting is widely used in every programming language to modify the program, and it also assists in the debugging phase for better clarity. This is not it; the discussion is further divided into part 2, where we have discussed the fundamental type casting operators in detail.

Recommended Readings:


Don’t stop here Ninja, get yourself enrolled in our Top-notch courses.

If you found this article advantageous, share it with your friends. Stay tuned for more amazing content.

Live masterclass