C++ Explicit Type Casting
Explicit type casting in C++ allows the programmer to manually convert a variable from one type to another using specific casting operators. This provides precise control over conversions and avoids unexpected implicit promotions.
1. static_cast
static_cast performs compile-time conversions between compatible types, such as int to float, float to int, or pointer upcasting.
#include <iostream>
using namespace std;
int main() {
int i = 10;
float f = static_cast<float>(i); // int to float
cout << "Integer: " << i << ", Float: " << f << endl;
double d = 9.78;
int j = static_cast<int>(d); // double to int
cout << "Double: " << d << ", Int: " << j << endl;
return 0;
}
2. dynamic_cast
dynamic_cast is used for safe runtime casting of pointers or references in an inheritance hierarchy, especially for polymorphic types (classes with virtual functions).
#include <iostream>
using namespace std;
class Base { public: virtual void show() {} };
class Derived : public Base { public: void display() { cout << "Derived class\n"; } };
int main() {
Base *b = new Derived();
Derived *d = dynamic_cast<Derived*>(b);
if(d) d->display();
else cout << "Cast failed" << endl;
delete b;
return 0;
}
3. reinterpret_cast
reinterpret_cast converts one pointer type to another, or integer to pointer and vice versa. Use with caution as it may produce implementation-dependent results.
#include <iostream>
using namespace std;
int main() {
int a = 65;
char *p = reinterpret_cast<char*>(&a);
cout << "First byte of integer a: " << *p << endl;
return 0;
}
4. const_cast
const_cast is used to add or remove the const or volatile qualifier from a variable.
#include <iostream>
using namespace std;
int main() {
const int x = 100;
int *ptr = const_cast<int*>(&x);
*ptr = 200; // Modifies value (undefined behavior if x is actually const)
cout << "Modified value: " << x << endl;
return 0;
}
5. Quick Comparison of Cast Types
| Cast | Use Case | Compile/Runtime | Safety |
|---|---|---|---|
| static_cast | Compatible types, numeric/pointer conversions | Compile-time | Safe if types compatible |
| dynamic_cast | Polymorphic pointer/reference conversion | Runtime | Safe, returns nullptr on failure |
| reinterpret_cast | Pointer reinterpretation | Compile-time | Unsafe, implementation-dependent |
| const_cast | Add/remove const/volatile | Compile-time | Safe, but modifying original const may be UB |
Conclusion
Explicit type casting in C++ provides fine-grained control over type conversions using static_cast, dynamic_cast, reinterpret_cast, and const_cast. Using the correct cast ensures safe and predictable behavior in programs.
Codecrown