⚙️ C++ Intermediate

What is type casting in C++?

Why Interviewers Ask This

Mid-level C++ roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

C++ provides four named cast operators that are safer and more descriptive than C-style casts: 1. static_cast — compile-time cast: checked at compile time. Safe for related types (numeric conversions, hierarchy casts, void* to typed pointer). double d = 3.14; int i = static_cast<int>(d); // 3 -- truncates Base* b = static_cast<Base*>(derivedPtr); // Upcast -- always safe void* v = ptr; int* p = static_cast<int*>(v); // void* to typed. 2. dynamic_cast — runtime polymorphic cast: validates at runtime via RTTI. Requires polymorphic type (at least one virtual function). Returns nullptr (pointer) or throws std::bad_cast (reference) on failure. Base* b = new Derived(); Derived* d = dynamic_cast<Derived*>(b); // OK if (!d) { /* b isn't a Derived */ } Animal* a = new Cat(); Dog* dog = dynamic_cast<Dog*>(a); // nullptr -- not a Dog. Avoid dynamic_cast in hot paths — has runtime overhead. Prefer virtual dispatch or std::variant. 3. const_cast — add/remove const: ONLY cast that can remove const. Very narrow use: call a non-const function on a const object when you know it won't modify: void print(char* s); // Legacy non-const param const char* cs = "hello"; print(const_cast<char*>(cs)); // Use only if print doesn't modify!. Undefined behavior to actually modify a const object via const_cast. 4. reinterpret_cast — bitwise reinterpretation: lowest-level, most dangerous. Reinterprets bit pattern as a different type. Only safe for specific patterns (round-trip through void*): int n = 42; char* bytes = reinterpret_cast<char*>(&n); // Examine bytes. C-style cast (avoid): (int)3.14 — tries static_cast, then const_cast, then reinterpret_cast — unpredictable and unsafe. Always use named casts.

Pro Tip

This topic has C++-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.