Type casting is the mechanism of converting a variable from one data type into another. While implicit conversions happen automatically, explicit conversions require deliberate programmer intent. Modern C++ introduced four explicit casting operators that completely replace dangerous C-style casts.
| Operator | Check Time | Primary Purpose & Safety |
|---|---|---|
static_cast<T>(v) |
Compile-time | Standard well-defined conversions (e.g. float to int, base to derived when type is certain). Safest general cast. |
dynamic_cast<T>(v) |
Runtime (RTTI) | Safe downcasting in inheritance hierarchies with virtual functions. Returns nullptr on failure. |
const_cast<T>(v) |
Compile-time | Adds or removes const or volatile qualifiers. (Never modify originally const data!). |
reinterpret_cast<T>(v) |
Compile-time | Low-level reinterpretation of bit patterns (e.g., pointer to integer, int* to char*). Highly dangerous. |
#include <iostream>
class Base { public: virtual ~Base() {} };
class Derived : public Base { public: void shout() { std::cout << "Derived!\n"; } };
int main() {
// 1. static_cast: Float to Int
double pi = 3.14159;
int intPi = static_cast<int>(pi); // 3
// 2. dynamic_cast: Polymorphic runtime validation
Base* b = new Derived();
if (Derived* d = dynamic_cast<Derived*>(b)) {
d->shout(); // Safe: cast succeeded!
}
delete b;
// 3. const_cast: Calling legacy API requiring non-const pointer
const int val = 100;
const int* ptr = &val;
int* modifiablePtr = const_cast<int*>(ptr);
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Understanding integer and floating-point sizes.
How dynamic_cast uses RTTI and virtual tables.
Pointer address casting and memory alignment.