On this page
  1. C++ Named Casts
  2. Overview
  3. The Five Named Casts
  4. Notes & Pitfalls
  5. Example

C++ Named Casts

Prev: new & delete | Up: builtins | Next: C-Style Casts (Legacy)
Rel: C-Style Casts (Legacy), Classes, Inheritance & virtual
Ref: cppreference — Explicit Type Conversion
Tags: #public #prog #cpp #builtins #tier/specialized


Overview

C++ replaces C's catch-all (T)expr cast with narrow, searchable named casts that state exact intent and catch accidental const stripping or unsafe pointer reinterpretation at compile time.

The Five Named Casts

Cast Purpose Safety
static_cast<T>(x) Well-defined conversions (numeric narrowing, enum↔int, upcast/known downcast) Compile-time checked
dynamic_cast<T>(x) Checked runtime downcast across polymorphic (virtual) hierarchies Returns nullptr (pointers) or throws std::bad_cast (refs)
const_cast<T>(x) Adds or removes const/volatile (mostly for legacy C APIs) Modifying a truly const object is UB
reinterpret_cast<T>(x) Low-level bit/pointer reinterpretation (e.g., std::byte* I/O, integer↔pointer) Easy to trigger strict-aliasing UB
std::bit_cast<T>(x) (<bit>, C++20) Reinterprets raw object representation between trivially copyable types of equal size Safe, constexpr, zero UB

Notes & Pitfalls

Example

#include <bit>
#include <cassert>
#include <cstdint>

int main() {
    double d = 3.9;
    int truncated = static_cast<int>(d);
    assert(truncated == 3);

    float f = 1.0f;
    auto bits = std::bit_cast<std::uint32_t>(f); // safe C++20 type punning
    assert(bits == 0x3f800000u);
}

Linked from

Related notes