Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Type Casting in C++?
3.
Types of Type Casting
3.1.
Implicit Type Conversion 
3.1.1.
Example:
3.2.
C++
3.3.
Explicit Type Conversion 
3.3.1.
Converting using assignment operator
3.4.
C++
3.4.1.
Conversion using cast operator
3.4.2.
Static Cast
3.4.3.
Dynamic Cast
3.4.4.
Const Cast
3.4.5.
Reinterpret_ Cast
4.
Program to use implicit type casting in C++
4.1.
C++
5.
Program to demonstrate the use of explicit type casting in C++
5.1.
C++
6.
Program to cast double data into int and float type using the cast operator
6.1.
C++
7.
Some different types of Type Casting
8.
Program to demonstrate the use of Dynamic Cast
8.1.
C++
9.
Program to use the Reinterpret Cast in C++
9.1.
C++
10.
Program to use the Const Cast in C++
10.1.
C++
11.
Application of Typecasting in C++
12.
Frequently Asked Questions
12.1.
What is the need for type casting?
12.2.
Give an example of a conversion that cannot be done by implicit type conversion?
12.3.
Which type of casting can perform the conversion from base class to derived class?
12.4.
What are the 4 casts in C++?
13.
Conclusion
Last Updated: Jul 9, 2024

Type Casting in C++

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

Introduction

C++ is a strong-typed programming language, which means that every variable has an associated data type before it is being used in the program. Typecasting is defined as the process of converting an expression from one type to another. Typecasting is a mechanism whose ultimate goal is to make variables of one data type work with variables of another data type in order to solve logical and mathematical expressions easily without any error and data loss. When a variable is typecast into another type, it is treated as a variable of the new data type by the compiler.

Type Casting in C++

What is Type Casting in C++?

Type casting in C++ is the process of converting a variable from one data type to another. This can happen in two ways: implicitly and explicitly. Implicit type casting is done automatically by the compiler when converting compatible data types, like from an int to a float. Explicit type casting, on the other hand, is performed by the programmer using specific casting operators. These include static_cast for general type conversions, dynamic_cast for safely converting pointers and references in inheritance hierarchies, const_cast for adding or removing const qualifiers, and reinterpret_cast for low-level reinterpreting of bit patterns. Explicit casting ensures precise control over data conversions.

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

Types of Type Casting

Implicit Type Conversion 

  • Implicit type conversions are also known as ‘Automatic Type Conversion”, these type conversions do not require any operator, these are performed automatically by the compiler on its own based on some predefined rules when a value is copied to a compatible type, without any external trigger/input from the user.

 

  • This takes place when in an expression there are variables of more than one data type, in such conditions, type promotion/ type conversion takes place to avoid any data loss.

 

  • During implicit conversion, it is possible to lose some information, i.e., overflow can occur ( when a long is converted to float ), signs can be lost when a signed is implicitly converted to unsigned.

 

  • The order/sequence of the automatic type conversion is 
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double 

 

Example:

  • C++

C++

#include<bits/stdc++.h>
using namespace std;
int main()
{
int x=5; // an integer x
char y='h'; // character y
// y implicitly converted to int
x=x+y; 
float z= x + 1.0; // x is implicitly converted to float

cout<<"Value of x is "<<x<<endl;
cout<<"Value of y is "<<y<<endl;
cout<<"Value of z is "<<z<<endl;
}

Output:

Value of x is 109
Value of y is h
Value of z is 110

You can try and compile with the help of online c++ compiler.

Explicit Type Conversion 

  • Explicit type conversion requires user intervention in order to change the data type of one variable to another,i.e., it allows the programmer to manually convert or typecast the data type of a variable to another. This is done when the required type conversion does not follow the implicit conversion rule.
     
  • The Explicitly type conversion can be done in two ways: Converting using assignment operator & Conversion using cast operator.


Converting using assignment operator

This is also considered as forceful casting as in this we define the required type (data type) in front of the expression in parenthesis.

Syntax: (final_data_type) expression

 

Example

  • C++

C++

#include<bits/stdc++.h>
using namespace std;
int main()
{
double x=5.8;
// explicitly converting from double to int
int diff= int(x) - 2;
cout<<"The Difference is "<<diff<<endl;
}

Output

The Difference is 3 

Conversion using cast operator

Cast operator is a unary operator which forces the conversion of one data type to the other. The following are the four types of casts in the C++ language:

Static Cast

  • No safety checks are performed in order to check whether the object being created is a full object of the destination type or not.
  • It is the duty of the programmer to ensure that the conversion should be safe.
  • It performs the casting of pointers to related classes. It can also perform conversions from base class to derived class and not only from a derived class to base class.
Syntax: static_cast <new_type> (expression)

 

Dynamic Cast

  • It can be used only with pointers and references to objects.
  • It needs to ensure that the result of the conversion is a valid, complete object of the requested class.
  • Base to Derived class conversions is not allowed with dynamic cast unless the base class is polymorphic.
  • When a class is polymorphic, a special checking during runtime is performed to ensure that the expression yields a valid, complete object of the requested class.
  • Can also cast null pointers, pointers to unrelated classes, pointers of any type to void pointers.
Syntax: dynamic_cast <new_type> (expression)

 

Const Cast

  • It manipulates the constness of the object, either to be removed or to be set.
  • It can be used to change the non-const class members inside a const member function.
  • It can also be used to pass const data to a function that does not receive const.
  • It is safer as compared to simple typecasting, as casting won't take place if the cast is not of the same type as the original object.
Syntax: const_cast  <new_type> (expression)

 

Reinterpret_ Cast

  • Any pointer type can be converted to another pointer type, even though they are from different classes, it doesn't check if the data pointed by pointer and pointer type is the same or not.
  • It can also cast pointers into integer types and vice versa.
  • It is used when we want to work with bits, but if we use this type of cast then it becomes a non-portable product.
Syntax : reinterpret_cast <new_type> (expression)

Program to use implicit type casting in C++

  • C++

C++

#include <iostream>

int main() {
int num1 = 10;
double num2 = 5.5;

// Implicit type casting: int is promoted to double for calculation
double result = num1 + num2;

std::cout << "Result: " << result << std::endl;

return 0;
}

Explanation:

  • When adding num1 (int) and num2 (double), the compiler implicitly converts num1 to a double to match the larger data type before performing the calculation.
  • This implicit conversion ensures accurate results and prevents potential data loss or type mismatches.

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

  • C++

C++

#include <iostream>

int main() {
double pi = 3.14159;

// Explicit type casting to int truncates decimal part
int approximatedPi = (int)pi;

std::cout << "Approximated pi (int): " << approximatedPi << std::endl;

// Explicit type casting to char
char asciiChar = (char)pi;

std::cout << "ASCII character: " << asciiChar << std::endl;
}

Explanation:

  • The cast operator (target_type) is used to explicitly convert values to different data types.
  • Casting pi to an int truncates the decimal part, resulting in 3.
  • Casting pi to a char interprets its value as an ASCII code, producing a non-printable character.

Program to cast double data into int and float type using the cast operator

  • C++

C++

#include <iostream>

int main() {
double value = 3.14159;

// Cast to int
int integerValue = (int)value;
std::cout << "Integer value: " << integerValue << std::endl; // Output: 3

// Cast to float
float floatValue = (float)value;
std::cout << "Float value: " << floatValue << std::endl; (approximate)
}

Explanation:

  • The cast operator is used to convert the double value to both int and float types.
  • Casting to int truncates the decimal part.
  • Casting to float preserves some decimal precision but might still involve slight approximation due to floating-point representation.

Some different types of Type Casting

  • Static Cast: Performs a compile-time type conversion for compatible types. It checks for validity at compile time and has a potential for failure at runtime.
  • Dynamic Cast: Used for downcasting in inheritance hierarchies. It checks for valid type compatibility at runtime and returns a null pointer if the cast fails.
  • Reinterpret Cast: Rewrites the bit pattern of one value to another type without any validation. It's risky and requires a deep understanding of memory layout.
  • Const Cast: Removes the const or volatile qualifier of a variable, allowing modification of constants. It should be used with extreme caution as it can lead to unexpected behavior.

Program to demonstrate the use of Dynamic Cast

  • C++

C++

#include <iostream>

class Base {};
class Derived : public Base {};

int main() {
Base* basePtr = new Derived();

// Dynamic cast to Derived
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);

if (derivedPtr) {
// Cast succeeded, use derivedPtr safely
std::cout << "Downcast successful!" << std::endl;
} else {
std::cout << "Invalid downcast." << std::endl;
}
}

Explanation:

  • Dynamic cast checks for valid downcasting at runtime.
  • If successful, it returns a pointer to the Derived object.
  • If not, it returns a null pointer, indicating an invalid cast.

Program to use the Reinterpret Cast in C++

  • C++

C++

#include <iostream>

int main() {
int value = 10;
float* floatPtr = reinterpret_cast<float*>(&value);

std::cout << "Interpreted value (might be invalid): " << *floatPtr << std::endl;
}

Explanation:

  • Reinterpret cast treats the memory location of value (int) as if it points to a float.
  • The resulting value depends on memory layout and might not be a valid float representation.
  • Reinterpret cast should be used cautiously due to potential undefined behavior.

Program to use the Const Cast in C++

  • C++

C++

#include <iostream>

int main() {
const int PI = 3.14159;

int* writablePi = const_cast<int*>(&PI);
*writablePi = 10;

std::cout << "Modified PI (might have unexpected behavior): " << PI << std::endl;
}

Explanation:

  • Const cast removes the const qualifier from a variable, allowing modification.
  • In this example, it's used on a constant PI (not recommended practice).
  • Modifying constants can lead to unexpected behavior or program crashes.

Application of Typecasting in C++

  • Function argument passing: When passing arguments of different types to functions, implicit or explicit casting might be needed to match function parameter types.
  • Data conversion: Converting data from one format to another (e.g., reading binary data and interpreting it as specific data types).
  • Interfacing with legacy code: Working with older code that might use different data types.
  • Memory management: In some low-level operations, reinterpret cast might be used for memory manipulation (cautiously and with a good understanding of memory layout).
  • Downcasting in inheritance: Using dynamic cast for safe downcasting in object-oriented programming hierarchies.

You can also do a free certification of Basics of C++.

Also Read - C++ Interview Questions

Frequently Asked Questions

What is the need for type casting?

It is used to convert the data type of variables in order to solve logical and mathematical expressions easily without any error and data loss.

Give an example of a conversion that cannot be done by implicit type conversion?

Converting a float to an int will truncate the fraction part hence losing the meaning of the value. Therefore this conversion cannot be converted by implicit type conversion properly, as they are not compatible with each other.

Which type of casting can perform the conversion from base class to derived class?

Static Cast can perform conversion from base class to derived class.

What are the 4 casts in C++?

The four casts in C++ are static_cast for general type conversions, dynamic_cast for safely converting pointers and references in inheritance hierarchies, const_cast for adding or removing const qualifiers, and reinterpret_cast for low-level reinterpreting of bit patterns between different data types.

Conclusion

In this blog, we discussed what type casting is and why we need it along with different types of type casting available in C++.

If you want to understand and learn more about type conversion and type casting concepts in C++, you can refer to this. Type conversion can also be done in python, you can study about it on this.

Live masterclass