Different Casts in Cpp
1. const_cast
const_castvoid modify(const int* p) {
// p points to a const int, but we know the original int is non-const
int* modifiable = const_cast<int*>(p);
*modifiable = 42; // OK only if the original object was non-const
}
int main() {
int x = 10;
modify(&x); // x is non-const, so modification is safe
// const int y = 20;
// modify(&y); // Would be undefined behavior (modifying a truly const object)
}2. static_cast
static_cast// Numeric conversion
double pi = 3.14159;
int intPi = static_cast<int>(pi); // Truncates to 3
// Upcasting (derived to base) – usually implicit, but explicit is fine
class Base {};
class Derived : public Base {};
Derived d;
Base* bp = static_cast<Base*>(&d); // Safe upcast
// Downcasting (base to derived) – unchecked, user must ensure correctness
Base* b = new Derived();
Derived* dp = static_cast<Derived*>(b); // OK because b really points to Derived
// If b pointed to a pure Base object, this would be undefined behavior3. reinterpret_cast
reinterpret_cast4. dynamic_cast
dynamic_castLast updated