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 ofstatic_cast,const_cast,reinterpret_cast, ordynamic_cast.- Value Category Rule: If
TYPEis a reference, the result of the cast is an lvalue; otherwise, the result is an rvalue.
The Four Named Casts at a Glance#
| Cast | Timing | Target / Purpose | Safety Check |
|---|---|---|---|
static_cast | Compile-time | Well-defined conversions (arithmetic, void* recovery, upcasting) | Validates convertible types at compile time |
const_cast | Compile-time | Adds or casts away low-level const / volatile | Compiler ensures types match except for constness |
reinterpret_cast | Compile-time | Low-level bit pattern reinterpretation | No safety check (platform-dependent, aliasing risks) |
dynamic_cast | Runtime | Safe Downcasting & Crosscasting in polymorphic hierarchies | Queries 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#
Forcing Floating-Point Division:
int i = 2, j = 1; double slope = static_cast<double>(j) / i; // Forces floating-point divisionInforming Compiler of Intentional Truncation:
double d = 97.6; int n = static_cast<int>(d); // Explicit cast turns off compiler truncation warningsRetrieving 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 viastatic_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_castto obtain write access and mutate an object originally defined asconstis 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, usingconst_castto 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
constmember function cast awayconstonthisto call the non-constversion — as that risks mutating an actuallyconstobject, causing Undefined Behavior. Always have the non-constoverload call theconstoverload.
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
intas characters.reinterpret_castis 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:
const_caststatic_castreinterpret_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_castanddynamic_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.