Type conversion is the process of converting a variable from one data type to another. In C++, there are two main types of type conversion:
The compiler automatically converts one data type to another when needed. For example:
int a = 5; double b = 6.7; double result = a + b; // 'a' is implicitly converted to double
Here, the integer a
is automatically converted to a double
before addition.
You can manually convert a variable from one type to another using casting. There are four types of casts in C++:
static_cast<type>(expression)
dynamic_cast<type>(expression)
(used with polymorphism)const_cast<type>(expression)
(to add/remove constness)reinterpret_cast<type>(expression)
(low-level cast)
For basic type conversion, static_cast
is commonly used.
static_cast
:double x = 9.99; int y = static_cast<int>(x); // y becomes 9 (fraction discarded)
The old C-style casting looks like this:
int y = (int)9.99; // y becomes 9
But static_cast
is preferred in modern C++ because it is safer and clearer.
#include <iostream> using namespace std; int main() { int a = 10; double b = 3.14; // Implicit conversion double sum = a + b; cout << "Sum (implicit conversion): " << sum << endl; // Explicit conversion (casting) int c = static_cast<int>(b); cout << "Value of b after casting to int: " << c << endl; return 0; }
static_cast
.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!