Syntax of Casting Operators
(new_return_type)variable_name
Let us understand this with a sample code:
#include <iostream>
int main()
{
float num = 456.21;
int x;
x = (int)num;
std::cout<<"\nBefore Casting:"<<num<<std::endl;
std::cout<<"\nAfter casting"<<x<<std::endl;
return 0;
}
Output:
You can try and compile with the help of online c++ compiler.
Implicit Casting Operators
Implicit Casting can automatically convert the data type without any programmer or user intervention. In this case, the compiler converts the data types without losing any information. But, it is only applicable if both the data types are compatible and the changed data type is in a higher order than the original data type.
The order of Casting is,
Source: Link
Sample code:
#include <iostream>
int main ()
{
int num = 500;
char ch = 'a';
int result = num + 'a';
std::cout<<"\nExplicit Type Casting"<<std::endl;
std::cout << "\nCasting char data type to integer data type ('a' to 500): " << result <<std::endl;
float val = num + 'A';
std::cout << "\nCasting from integer data type to float type: " << val <<std::endl;
return 0;
}
Output:
In the above code, we can see the integer variable num was added to the char ch. It could happen because "a" has an ASCII integer value of 97; therefore, the compiler automatically typecast the char to integer data type.
In further lines of code, the compiler automatically converted the ASCII integer value of A, i.e., 65, to float data type and printed the result.
Explicit Casting Operators
Explicit Casting is done by the programmer manually according to their requirements. It is not required to check the order of data types; the coder can upgrade or downgrade the data type according to their own choice.
Sample Code:
#include <iostream>
int main ()
{
int num = 1024;
int a = 5;
float ans;
ans = (float)num / a;
std::cout<<"\nImplicit Type Casting"<<std::endl;
std::cout << "Dividing two numbers:" << num / a <<std::endl;
std::cout<<"\nExplicit Type Casting"<<std::endl;
std::cout << "Dividing the two numbers: " << ans <<std::endl;
return 0;
}
Output:
In the above example, it can be seen when Implicit Casting was applied, there was some data loss, while during explicit Casting, no data was lost.
Types of Casting Operators
In C++, according to the program's requirements, casting operators to force one data type to be converted to another data type. There are four types of casting operators:
- Static Casting Operator
- Dynamic Casting Operator
- Const Casting Operator
- Reinterpret Casting Operator
Static Casting Operators
The static_cast is a method to cast the data types of variables. They are checked at the compile time, and the programmer is solely responsible for ensuring that the change was successful without any data loss.
Syntax:
static_cast <new_data_type>(variable);
Sample Code
#include <iostream>
int main()
{
float f = 16.5;
int a = f;
int b = static_cast<int>(f);
std::cout <<"Number after static casting is :"<< b;
}
Output:
In the above sample code, we can see that using the static_cast keyword the float variable f was casted to an integer value.
Dynamic Casting Operator
The dynamic_cast is a method to convert the data types of variables of a class pointer and references. They are checked at run-time, and it returns a NULL value if the Casting is unsuccessful.
Syntax:
new_data_type* new_pointer = dynamic_cast<new_data_type>(pointer);
Sample Code:
#include<iostream>
using namespace std;
class Class1
{
public:
virtual void print () const
{
cout << "This is from Class 1.\n";
}
};
class Class2
{
public:
virtual void print () const
{
cout << "This is from Class 2.\n";
}
};
class Class3:public Class1, public Class2
{
public:
void print () const
{
cout << "This is from Class 3.\n";
}
};
int main ()
{
Class1 *a = new Class1;
Class2 *b = new Class2;
Class3 *c = new Class3;
a->print ();
b->print ();
c->print ();
b = dynamic_cast < Class2 * >(a); //This cast will be failed
if (b)
b->print ();
else
cout << "No Class 2.\n";
a = c;
a->print (); //Printing from Class3
b = dynamic_cast < Class2 * >(a); //Successfully casting is done
if (b)
b->print ();
else
cout << "No Class 2.\n";
}
Output:
In the above code, you can see the implementation of dynamic_cast keyword. The keyword can only be used in inheritance.
Const Casting Operator
The const_cast is a method to handle the const functioning of the source pointer. We can either set a const pointer to a non-const pointer or remove the const from the const pointer.
Syntax:
const_cast<data_type>pointer;
Sample Code:
#include<iostream>
using namespace std;
int fun(int* ptr)
{
return (*ptr + 100);
}
int main(void)
{
const int num = 500;
const int *ptr = #
int *new_ptr = const_cast <int *>(ptr);
cout << fun(new_ptr);
return 0;
}
Output:
Reinterpret Cast Operator
The reinterpret_cast is a method to cast a pointer to another pointer even if the pointer and the data it is pointed towards are the same.
Syntax:
reinterpret_cast<data_type>pointer;
Sample Code:
#include <iostream>
using namespace std;
int main()
{
int* num = new int(100);
char* ch = reinterpret_cast<char*>(num);
cout << *num << endl;
cout << *ch << endl;
cout << num << endl;
cout << ch << endl;
return 0;
}
Output:
In the above code, the reinterpret_cast keyword was able to typecast a pointer value to another datatype. This type of casting is used when we have to work with bits.
Frequently Asked Questions
When should a type cast be used?
Typecasting is used in computer programming to ensure a function correctly processes variables. When a variable is typecast into a different type, the compiler treats the variable as the new data type.
Does type casting affect the data?
Sometimes, data is lost when the Casting is done from higher to lower order.
Can you cast variables among classes?
Yes, we can cast variables among classes with the help of Dynamic Casting Operator.
When do you need to use type-conversions?
We need to use Casting when the value is stored beyond the highest range, and it does not support that data type. Also, to reduce the memory in use, we apply casting operators.
Conclusion
In this article, we have extensively discussed the casting operators in C++. We hope that this blog has helped you enhance your knowledge and aspects that you should keep in mind while dealing with the operators in C++; here are the articles on operators. If you want to explore and learn big data, make sure to check out this. Do upvote our blog to help other ninjas grow.
Learning never stops, and to feed your quest to learn and become more skilled, head over to our practice platform Coding Ninjas Studio to practice top problems, you can check SQL problems here, attempt mock tests, read interview experiences, and you can also check our guided path for the coding interview and much more!