C++ CAST OPERATOR MATRIX:
┌──────────────────┬────────────────────────────────────────────────────────┐
│ Cast Operator │ Primary Purpose & Safety │
├──────────────────┼────────────────────────────────────────────────────────┤
│ static_cast │ Compile-time conversions (int float, upcast, etc.) │
│ dynamic_cast │ Runtime safe polymorphic downcasting (requires vtable) │
│ const_cast │ Adds or removes const / volatile qualifier │
│ reinterpret_cast │ Low-level bit pattern reinterpretation (pointers/ints) │
└──────────────────┴────────────────────────────────────────────────────────┘C++ Type Conversion: Automatic and Explicit Value Transformation
Direct Answer & Core Concept
Detailed Explanation & Mechanics
1. The Four C++ Named Casts:
2. Why C-Style Casts `(int)x` are Discouraged:
C-style casts silently perform a combination of const_cast, static_cast, and reinterpret_cast without compiler safety checks, masking dangerous type conversions.
Runnable Code Example: C++ Type Conversion
C++20 / C++23#include <iostream>
class Base {
public:
virtual ~Base() = default; // Polymorphic base
};
class Derived : public Base {
public:
void printDerived() { std::cout << "Derived instance active!
"; }
};
int main() {
// 1. static_cast (numeric conversion)
double preciseValue = 45.78;
int roundedValue = static_cast<int>(preciseValue);
std::cout << "static_cast result: " << roundedValue << "
";
// 2. dynamic_cast (polymorphic runtime verification)
Base* basePtr = new Derived();
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
if (derivedPtr) {
derivedPtr->printDerived();
}
delete basePtr;
return 0;
}Common C++ Technical Interview Questions & Answers
Interview PrepQ: What does dynamic_cast return if a pointer downcast fails?
Q: When is reinterpret_cast legitimately used?
Key Takeaways, Modern Best Practices & Idioms
C++ Best Practices & Production Rules
(Type)val; always use explicit C++ named casts.2. Prefer
static_cast for standard numeric and pointer upcasts.3. Check
dynamic_cast pointer results against nullptr before dereferencing.