This part of the guide will cover the process of variable type conversion in C++ programming. Type casting involves changing the data type of a variable from one to another within a program. There are two methods of performing type casting: automatic conversion by the compiler and manual conversion by the programmer or user. Type Casting is synonymous with Type Conversion.
For instance, if the provided data is of integer type and requires conversion to float type, we must perform a manual typecasting from int to float. This process of casting between different data types is known as Type Casting in C++.
int num = 5;
float x;
x = float(num);
x = 5.0
2 nd example:
float num = 5.25;
int x;
x = int(num);
Output: 5
Type Casting is categorized into two forms: Implicit conversion, also known as Implicit Type Casting, and Explicit Type Conversion, which is also referred to as Explicit Type Casting.
Implicit Type Casting or Implicit Type Conversion
- It is known as the automatic type casting.
- 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.
- All data type is automatically upgraded to the largest type without losing any information.
- It can only apply in a program if both variables are compatible with each other.
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 generate a sample scenario to illustrate the conversion of a variable to another type through implicit type casting within the C++ programming language.
#include <iostream>
using namespace std;
int main ()
{
short x = 200;
int y;
y = x;
cout << " Implicit Type Casting " << endl;
cout << " The value of x: " << x << endl;
cout << " The value of y: " << y << endl;
int num = 20;
char ch = 'a';
int res = 20 + 'a';
cout << " Type casting char to int data type ('a' to 20): " << res << endl;
float val = num + 'A';
cout << " Type casting from int data to float type: " << val << endl;
return 0;
}
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 provided code snippet, we initialized a variable 'x' of type short with a value of 200, and an integer variable 'y'. Subsequently, we assigned the value of 'x' to 'y'. The compiler performed an implicit conversion from the short data type of 'x' to the integer data type of 'y', resulting in 'y' holding the value 200.
In the following statements, we initialized an integer type variable num to 20, and a character type variable ch to 'a', which corresponds to an ASCII value of 97. Subsequently, we performed an addition operation on these two variables to demonstrate implicit conversion, resulting in the expression yielding 117.
In the third scenario, we assign the value 20 to the integer variable num and 65 to the character variable ch. Subsequently, we assign the outcome to the float variable val. Consequently, the compiler automatically converts the expression's result to the float data type.
Explicit Type Casting or Explicit Type Conversion
- It is also known as the manual type casting in a program.
- 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.
- It does not require checking the compatibility of the variables.
- In this casting, we can upgrade or downgrade the data type of one variable to another in a program.
- It uses the cast operator to change the type of a variable.
Syntax of the explicit type casting
(type) expression;
type: It denotes the user-specified information that transforms the provided expression.
It symbolizes a constant value, variable, or an expression that undergoes a data type conversion.
For instance, if we have a floating-point number like 4.534, the process to convert it into an integer value would be as follows:
int num;
num = (int) 4.534; // cast into int data type
cout << num;
When the preceding instructions are run, the floating-point number will be converted to an integer data type utilizing the cast function. Subsequently, the float value is allocated to an integer variable "num" which truncates the decimal part, revealing solely 4 as the integer value.
A sample code showcasing the application of explicit type conversion in C++:
#include <iostream>
using namespace std;
int main() {
double myDouble = 3.14;
int myInt = static_cast<int>(myDouble);
cout << "Double value: " << myDouble << endl;
cout << "Int value after casting: " << myInt << endl;
return 0;
}
Let's develop a basic program that converts a variable of one data type into another using explicit type casting in the C++ programming language.
#include <iostream>
using namespace std;
int main ()
{
// declaration of the variables
int a, b;
float res;
a = 21;
b = 5;
cout << " Implicit Type Casting: " << endl;
cout << " Result: " << a / b << endl; // it loses some information
cout << " \n Explicit Type Casting: " << endl;
// use cast () operator to convert int data to float
res = (float) 21 / 5;
cout << " The value of float variable (res): " << res << endl;
return 0;
}
Output:
Implicit Type Casting:
Result: 4
Explicit Type Casting:
The value of float variable (res): 4.2
In the provided code snippet, we declare two integer variables, namely a and b, initialized with the values 21 and 2 respectively. Subsequently, the division operation a divided by b (21/2) is performed, resulting in a value of 4 of integer type.
In the subsequent expression, a float type variable named res is defined to retain the outcomes of variables a and b without any loss of data by employing the cast operator within the explicit type cast technique.
A program that demonstrates casting a double data type into an integer and float type using the cast operator is shown below:
#include <iostream>
using namespace std;
int main() {
double myDouble = 3.14;
// Casting double to int
int myInt = static_cast<int>(myDouble);
cout << "Double to Int: " << myInt << endl;
// Casting double to float
float myFloat = static_cast<float>(myDouble);
cout << "Double to Float: " << myFloat << endl;
return 0;
}
Let's explore an instance where we calculate the area of a rectangle by converting double data into float and integer types within C++ programming.
#include <iostream>
using namespace std;
int main ()
{
// declaration of the variables
double l, b;
int area;
// convert double data type to int type
cout << " The length of the rectangle is: " << endl;
cin >> l;
cout << " The breadth of the rectangle is: " << endl;
cin >> b;
area = (int) l * b; // cast into int type
cout << " The area of the rectangle is: " << area << endl;
float res;
// convert double data type to float type
cout << " \n \n The length of the rectangle is: " << l << endl;
cout << " The breadth of the rectangle is: " << b << endl;
res = (float) l * b; // cast into float type
cout << " The area of the rectangle is: " << res;
return 0;
}
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:
- Static_cast
- dynamic_cast
- const_cast
- reinterpret_cast
Static Cast:
The static_cast is a straightforward compile-time conversion that changes one data type to another. This implies that it doesn't verify the data type during runtime to validate the cast. Therefore, it is the programmer's or user's duty to guarantee the safety and validity of the conversion.
The static_cast operator is sufficiently powerful to handle all the conversions executed by the implicit cast. It also facilitates conversions between pointers of interrelated classes (upcasting - > from a derived class to a base class or downcasting - > from a base class to a derived class).
Syntax of the Static Cast
static_cast < new_data_type> (expression);
Program to demonstrate the use of the Static Cast
Let's construct a basic illustration to demonstrate the utilization of the static cast for type casting in C++ programming.
#include <iostream>
using namespace std;
int main ()
{
// declare a variable
double l;
l = 2.5 * 3.5 * 4.5;
int tot;
cout << " Before using the static cast:" << endl;
cout << " The value of l = " << l << endl;
// use the static_cast to convert the data type
tot = static_cast < int > (l);
cout << " After using the static cast: " << endl;
cout << " The value of tot = " << tot << endl;
return 0;
}
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 dynamiccast operator is a type of cast used during runtime to convert one type of variable to another, specifically for class pointers and references. This operator verifies the validity of the conversion at runtime, and if the conversion is unsuccessful, it returns a NULL value. The dynamiccast operation relies on the RTTI (Runtime Type Identification) mechanism for its functionality.
Below is a program showcasing the application of Dynamic Cast in C++:
#include <iostream>
class Base {
public:
virtual void display() {
std::cout << "This is the Base class." << std::endl;
}
};
class Derived : public Base {
public:
void display() override {
std::cout << "This is the Derived class." << std::endl;
}
};
int main() {
Base* basePtr = new Derived();
// Using dynamic_cast to safely downcast
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
if (derivedPtr) {
std::cout << "Downcasting successful:" << std::endl;
derivedPtr->display();
} else {
std::cout << "Downcasting failed." << std::endl;
}
delete basePtr;
return 0;
}
In this demonstration, a Base class and a Derived class are created. The Derived class inherits from the Base class. The program showcases the use of dynamic_cast to safely downcast a pointer from the Base class to the Derived class. If the downcast is successful, it calls the overridden display function of the Derived class.
Let's develop a basic program to execute the dynamic_cast operation in the C++ programming language.
#include <iostream>
using namespace std;
class parent
{
public: virtual void print()
{
}
};
class derived: public parent
{
};
int main ()
{
// create an object ptr
parent *ptr = new derived;
// use the dynamic cast to convert class data
derived* d = dynamic_cast <derived*> (ptr);
// check whether the dynamic cast is performed or not
if ( d != NULL)
{
cout << " Dynamic casting is done successfully";
}
else
{
cout << " Dynamic casting is not done successfully";
}
}
Output:
Dynamic casting is done successfully.
Reinterpret Cast Type
The reinterpretcast type casting is employed to convert a pointer to a different type of pointer, regardless of whether the original pointer and the new pointer types are compatible with each other. This means that reinterpretcast does not verify if the pointers or the data they point to are of the same type. Additionally, it can convert a pointer to an integer type or vice versa.
Syntax of the reinterpret_cast type
reinterpret_cast <type> expression;
Program to use the Reinterpret Cast in C++
Let's create a program to showcase how to convert a pointer using the reinterpret in the C++ programming language.
#include <iostream>
using namespace std;
int main ()
{
// declaration of the pointer variables
int *pt = new int (65);
// use reinterpre_cast operator to type cast the pointer variables
char *ch = reinterpret_cast <char *> (pt);
cout << " The value of pt: " << pt << endl;
cout << " The value of ch: " << ch << endl;
// get value of the defined variable using pointer
cout << " The value of *ptr: " << *pt << endl;
cout << " The value of *ch: " << *ch << endl;
return 0;
}
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 operator is utilized to modify the const behavior of the source pointer. This allows us to alter constness in two ways: either assigning a const pointer to a non-const pointer or removing the const qualifier from a const pointer.
Syntax of the Const Cast type
const_cast <type> exp;
Program to use the Const Cast in C++
Let's create a program that demonstrates how to convert a source pointer to a non-constant pointer using the const_cast operator in the C++ programming language.
#include <iostream>
using namespace std;
// define a function
int disp(int *pt)
{
return (*pt * 10);
}
int main ()
{
// declare a const variable
const int num = 50;
const int *pt = # // get the address of num
// use const_cast to chnage the constness of the source pointer
int *ptr = const_cast <int *> (pt);
cout << " The value of ptr cast: " << disp(ptr);
return 0;
}
Output:
The value of ptr cast: 500