On this page
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
- Prefer named C++ casts over C-style
(T)x:static_castfor checked value/hierarchy conversions,dynamic_castfor polymorphic runtime checks,const_castonly for legacy C APIs, andstd::bit_cast(C++20) instead ofreinterpret_castfor type punning. - Avoid UB with
const_cast: Modifying an object originally declaredconstis undefined behavior.
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
- tuts/cpp/builtins/c_style_casts Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/new_and_delete Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins Linked here; links to this page; shared tags: #builtins, #cpp, #prog
- tuts/cpp/builtins/classes_and_virtual Linked here; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/auto shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/concepts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/constexpr shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/lambdas shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/move_semantics shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/namespaces shared tags: #builtins, #cpp, #prog, #tier