Last Updated on April 19, 2023 by Prepbytes
C++ is a strongly typed language, which means that variables must be declared with a specific data type. However, there may be times when we need to convert a variable from one data type to another. This is where type casting in C++ comes in. With the help of type casting in C++, we can solve this problem of converting one data type into another. This article will discuss type casting in C++, types of type casting in C++, and the applications of type casting in C++.
What is Type Casting in C++?
Type casting in C++ refers to the process of converting a value of one data type to another data type. This can be useful in situations where we need to change the type of a variable to perform a certain operation or pass it to a function that requires a different data type. There are two types of type casting in C++: implicit and explicit type casting.
Implicit Type Casting
Implicit type casting occurs automatically when the compiler converts a value from one data type to another. This happens when a value is assigned to a variable of a different data type, or when an expression involving different data types is evaluated. For example, if we assign an integer value to a float variable, the compiler will automatically convert the integer value to a float value.
Implicit type casting is useful because it simplifies coding and can help avoid errors. However, it can also lead to unexpected behavior and loss of precision. For example, when an integer is converted to a float, some of the precision is lost.
Example of Implicit Type Casting
In this section, we will discuss an example of implicit type casting in C++.
#include <iostream> using namespace std; int main () { short x = 300; int y; y = x; cout << " Implicit Type Casting " << endl; cout << " The value of y: " << y << endl; cout << " The value of x: " << x << endl; int num = 30; char ch = 'a'; int res = 30 + 'b'; float val = num + 'B'; cout << " Type casting from int data to float type: " << val << endl; cout << " Type casting char to int data type ('b' to 30): " << res << endl; return 0; }
Output
Implicit Type Casting
The value of y: 300
The value of x: 300
Type casting from int data to float type: 96
Type casting char to int data type ('b' to 30): 128
Explanation of the above example
In the above example, we have declared a variable x of short data type and a variable y of int type when we assign x yo y the compiler automatically converts the datatype of x into y.
In the next example, we have taken character summation with an integer and stored the answer in float the compiler automatically gives us the correct answer by typecasting the variables.
In the other example, we have declared an integer and a character and when we are adding these two we are getting the integer as a result as the value of the character is automatically converted into its corresponding integer value.
Explicit Type Casting
Explicit type casting occurs when the developer manually converts a value from one data type to another. This is done using the cast operator, which is represented by parentheses enclosing the target data type. For example, to convert an integer value to a float, we can use the following code:
Explicit type casting is useful when precision is important or when data needs to be converted between different data types. However, it should be used with caution, as it can lead to errors if not used correctly.
Example of Explicit Type Casting
Now we will discuss the example of explicit type casting in C++.
#include <iostream> using namespace std; int main () { int x, y; float ans; x = 78; y = 157; cout << " Implicit Type Casting: " << endl; cout << " Result: " << y/x << endl; cout << " \n Explicit Type Casting: " << endl; ans = (float) 157 / 78; cout << " The value of float variable (ans): " << ans << endl; return 0; }
Output
Implicit Type Casting:
Result: 2
Explicit Type Casting:
The value of float variable (ans): 2.01282
Explanation of the above example
In the above example we have taken two variables x and y of int type and when we are dividing them the automatic typecasting is int and we get the required answer in integer format. But when we are explicitly typecasting the answer in float value so after performing the same operation we get the answer in float value.
Types of Explicit Type Casting
There are several types of explicit type casting in C++. Let’s explore each type in more detail.
Static Cast
The static cast is the most commonly used type of explicit type casting in C++. It is used to convert between related data types, such as integer to float or pointer to the base class to pointer to the derived class. The static cast is also used to perform upcasting and downcasting between class hierarchies.
Here is an example of using the static cast to convert an integer value to a float:
Example of Static Cast
Here we have discussed the example of the static cast.
#include <iostream> using namespace std; int main() { float f = 5.5; int i ; i = f; cout<<"i = "<<i<<endl; i = static_cast<int> (f); cout<<"i = "<<i<<endl; return 0; }
Output
i = 5
i = 5
Explanation of the above example
In the above example, we have implicit and static typecasting in C++.
Dynamic Cast
The dynamic cast is used to perform downcasting between class hierarchies. It is used when we need to convert a pointer to a base class to a pointer to a derived class. The dynamic cast ensures that the cast is safe by performing a run-time check to ensure that the conversion is valid.
Example of Dynamic Cast
In this section, we will discuss the example of a dynamic cast.
#include<bits/stdc++.h> using namespace std; class Base{ virtual void f(){ } }; class Derived : public Base{}; int main(){ Derived dobj; Base bobj; Base & rb = dynamic_cast<Base&>(dobj); Derived & rd = dynamic_cast<Derived*>(bobj); return 0; }
Output
prog.cpp: In function ‘int main()’:
prog.cpp:13:47: error: cannot dynamic_cast ‘bobj’ (of type ‘class Base’) to type ‘class Derived*’ (source is not a pointer)
Derived & rd = dynamic_cast(bobj);
Explanation of the above example
We make the impossible attempt to cast the base object into the derived object. Because giving it to a derived class reference would be the same as asserting that the base class is a capable replacement for a derived class and can perform all of the derived class’s capabilities, which is untrue.
Reinterpret Cast
The reinterpret cast is used to perform low-level type conversions that are not supported by the other types of explicit type casting. It is used to convert between unrelated data types, such as converting a pointer to an integer or vice versa. The reinterpret cast does not perform any type of checking and can lead to undefined behavior if used incorrectly.
Example
Now we will discuss the example of reinterpret cast.
#include<bits/stdc++.h> using namespace std; int main(){ int a = 70; // ASCII value of F = 70 int *int_pointer = &a; char* char_pointer = reinterpret_cast<char *>(int_pointer); cout<<*char_pointer<<endl; return 0; }
Output
F
Explanation of the above example
In the above example with the help of reinterpret_cast, the integer pointer was transformed into a character pointer.
Const Cast
The const cast is used to remove or add const qualifiers to a data type. It is used when we need to modify a variable that is declared as const, or when we need to assign a non-const variable to a const variable.
Example
Below is an example of the above-mentioned approach:
#include<bits/stdc++.h> using namespace std; int fun( int* ptr){ return (*ptr); } int main(){ const int val = 18; const int *ptr = &val; int* ptr1 = const_cast<int*>(ptr); cout<<fun(ptr1); return 0; }
Output
18
Explanation of the above example
In the above example we have used const variables and to typecast it we have used const cast.
Application of Typecasting in C++
Some of the applications of typecasting in C++.
- We can use typecasting for the interconversion of datatype.
- We can use typecasting in C++ for polymorphism as the object can take many forms so we use them for conversion.
- It is also used for memory management as we can convert pointers from one form to another.
Conclusion
In conclusion, type casting in C++ is an important concept that allows developers to convert one data type to another. It is a powerful tool that enables developers to manipulate data and perform operations that would otherwise be impossible. In this article, we explored the different types of type casting in C++ and their uses. We learned that implicit type casting occurs automatically when the compiler converts a value from one data type to another, while explicit type casting occurs when the developer manually converts a value from one data type to another. We also learned about the four types of explicit type casting in C++: static cast, dynamic cast, reinterpret cast, and const cast. With proper understanding and implementation, type casting in C++ can greatly enhance our efficiency and effectiveness in writing programs.
Frequently Asked Questions
Here are some of the frequently asked questions about typecasting in C++.
Q1. What is type promotion in C++?
Ans: Type promotion is the process where the compiler automatically promotes a value to a higher data type to perform a calculation.
Q2. What is type demotion in C++?
Ans: Type demotion is the process where the compiler automatically demotes a value to a lower data type to perform a calculation.
Q3. What is type-safe language?
Ans: A type-safe language is a programming language that prevents type errors, such as incompatible data types, at compile-time or runtime.
Q4. What is a type-unsafe language?
Ans: A type-unsafe language is a programming language that does not prevent type errors, such as incompatible data types, at compile-time or runtime.
Q5. What are the advantages of using type-safe languages?
Ans: The advantages of using type-safe languages include better program reliability, fewer runtime errors, and increased program security.