C++ Type Casting
Type casting in C++ is a method to convert a variable from one data type to another. C++ provides several ways to perform type conversion: implicit (automatic) and explicit (manual) casting. Advanced C++ introduces four types of explicit casting operators for safer and more controlled conversions.
Types of Type Casting
- Use static_cast for simple, safe conversions.
- Use dynamic_cast for safe runtime downcasting of polymorphic types.
- Use const_cast only to add or remove
const; avoid modifying original const variables. - Use reinterpret_cast carefully for low-level pointer manipulations; it is not type-safe.
Next Topic
Next, learn about RAII (Resource Acquisition Is Initialization) in C++.
- static_cast<> – Used for compile-time type conversions, e.g., numeric conversions or pointer upcasting.
- dynamic_cast<> – Used for safe downcasting of polymorphic types. Checks at runtime using RTTI (Run-Time Type Information).
- const_cast<> – Used to add or remove
constorvolatilequalifiers. - reinterpret_cast<> – Used for low-level reinterpreting of bit patterns. Typically used for pointer conversions.
Example: static_cast
#include <iostream>
using namespace std;
int main() {
double pi = 3.14159;
int intPi = static_cast<int>(pi); // Convert double to int
cout << "Original: " << pi << ", After static_cast: " << intPi << endl;
return 0;
}
Output
Original: 3.14159, After static_cast: 3
Example: dynamic_cast
#include <iostream>
using namespace std;
class Base {
public:
virtual void display() { cout << "Base class" << endl; }
};
class Derived : public Base {
public:
void display() override { cout << "Derived class" << endl; }
};
int main() {
Base* b = new Derived();
Derived* d = dynamic_cast<Derived*>(b); // Safe downcast
if(d) d->display();
else cout << "Conversion failed" << endl;
delete b;
return 0;
}
Output
Derived class
Example: const_cast
#include <iostream>
using namespace std;
int main() {
const int x = 10;
int* y = const_cast<int*>(&x); // Remove const
*y = 20; // Modifying const variable (unsafe, but possible)
cout << "x: " << x << endl;
return 0;
}
Example: reinterpret_cast
#include <iostream>
using namespace std;
int main() {
int x = 65;
char* ch = reinterpret_cast<char*>(&x); // Treat int pointer as char pointer
cout << "Character representation: " << *ch << endl;
return 0;
}
Output
Character representation: A
Important Notes
- Use static_cast for simple, safe conversions.
- Use dynamic_cast for safe runtime downcasting of polymorphic types.
- Use const_cast only to add or remove
const; avoid modifying original const variables. - Use reinterpret_cast carefully for low-level pointer manipulations; it is not type-safe.
Next Topic
Next, learn about RAII (Resource Acquisition Is Initialization) in C++.