Type Conversions and Casts#

Based on C++ Primer, 5th ed. Section 4.11 (Type Conversions).

Named Cast Syntax#

C++ introduces four explicit named casts:

CASTNAME<TYPE>(EXPRESSION);
  • CASTNAME: One of static_cast, const_cast, reinterpret_cast, or dynamic_cast.
  • Value Category Rule: If TYPE is a reference, the result of the cast is an lvalue; otherwise, the result is an rvalue.

The Four Named Casts at a Glance#

CastTimingTarget / PurposeSafety Check
static_castCompile-timeWell-defined conversions (arithmetic, void* recovery, upcasting)Validates convertible types at compile time
const_castCompile-timeAdds or casts away low-level const / volatileCompiler ensures types match except for constness
reinterpret_castCompile-timeLow-level bit pattern reinterpretationNo safety check (platform-dependent, aliasing risks)
dynamic_castRuntimeSafe Downcasting & Crosscasting in polymorphic hierarchiesQueries RTTI (Run-Time Type Identification) via vptr → vtable

1. static_cast#

Used for any well-defined type conversion that does not involve casting away const.

Common Use Cases#

  1. Forcing Floating-Point Division:

    int i = 2, j = 1;
    double slope = static_cast<double>(j) / i; // Forces floating-point division
    
  2. Informing Compiler of Intentional Truncation:

    double d = 97.6;
    int n = static_cast<int>(d); // Explicit cast turns off compiler truncation warnings
    
  3. Retrieving a Pointer from void*:

    double d = 97.6;
    void *vp = &d;
    double *dp = static_cast<double*>(vp); // Valid: restores original typed pointer
    // int *ip = static_cast<int*>(vp);   // Compiles, but Undefined Behavior if dereferenced
    

When restoring a pointer stored in a void* back to its original type via static_cast, the pointer value is guaranteed to be preserved. However, the programmer must ensure the target type is the actual type of the object.


2. const_cast#

The only cast that can change low-level const or volatile qualifiers.

const char *pc = "hello";
char *p = const_cast<char*>(pc); // Casts away const

Undefined Behavior Warning#

  • Modifying a const object: Using const_cast to obtain write access and mutate an object originally defined as const is Undefined Behavior (UB):
    const int val = 10;
    int *p = const_cast<int*>(&val);
    *p = 20; // Undefined Behavior: val may reside in read-only memory
    
  • Legal use: If the underlying object was originally non-const, using const_cast to regain write access is legal.

Typical Use Case#

const_cast is most useful in overloaded const and non-const member functions sharing identical lookup/validation logic, where the non-const version delegates to the const member function to avoid code duplication:

class Buffer {
public:
  // 1. const member function: implements the core lookup/validation logic once
  const char& operator[](size_t idx) const {
    // Bounds checking, logging, and read logic
    return data_[idx];
  }

  // 2. non-const member function: reuses the const version
  char& operator[](size_t idx) {
    // (1) static_cast<const Buffer&>(*this) (or C++17 std::as_const(*this)) adds const
    //     so overload resolution calls the const operator[] instead of infinite recursion
    // (2) const_cast<char&>(...) strips const from the returned reference
    //     (100% safe because *this in this non-const member function is guaranteed to be non-const!)
    return const_cast<char&>(
        static_cast<const Buffer&>(*this)[idx]
    );
  }

private:
  std::string data_;
};

⚠️ Warning: Never do the reverse — having the const member function cast away const on this to call the non-const version — as that risks mutating an actually const object, causing Undefined Behavior. Always have the non-const overload call the const overload.


3. reinterpret_cast#

Performs a low-level, machine-dependent reinterpretation of the bit pattern of its operands.

int n = 42;
int *ip = &n;
char *pc = reinterpret_cast<char*>(ip); // Reinterprets int pointer as char pointer
  • Inherent Danger: Dereferencing the reinterpreted pointer treats the raw bytes of an int as characters. reinterpret_cast is inherently machine-dependent and circumvents the type system.
  • Strict Aliasing: Accessing an object through a pointer of an incompatible type violates strict aliasing rules, resulting in optimizer-induced Undefined Behavior.

4. dynamic_cast#

Covered in detail in C++ Primer Section 19.2: Run-Time Type Identification (RTTI). Safely converts pointers and references at runtime along a polymorphic class hierarchy — classes with at least one virtual function — by inspecting RTTI via vptr → vtable. For Upcast vs. Downcast, why virtual is required, and the full scope of dynamic_cast including Crosscast with code examples, see OOP: Upcast vs. Downcast.


Old-Style Casts#

Early C++ supported two old-style cast notations:

TYPE(EXPRESSION);   // Function-style cast notation
(TYPE)EXPRESSION;   // C-language-style cast notation

Fallback Order#

An old-style cast attempts the following named casts in order:

  1. const_cast
  2. static_cast
  3. reinterpret_cast

If neither a const_cast nor a static_cast is legal, the old-style cast silently falls back to a reinterpret_cast. This makes old-style casts hazardous and difficult to audit.


Core Advice: Avoid Casts#

“Casts interfere with the normal type-checking system. As a result, we strongly recommend that programmers avoid casts.” - C++ Primer, 5th ed.

  • reinterpret_cast: Always hazardous; avoid whenever possible.
  • const_cast: Useful in overloaded functions, but other uses often indicate a design flaw.
  • static_cast and dynamic_cast: Should be needed infrequently. Re-evaluate design before introducing them.
  • Mitigation: When a cast is unavoidable, limit the scope of the cast value and clearly document all underlying type assumptions.