~/okanakyuz
← all posts

Cast in C++

My short notes on the four C++ cast operators (static_cast, reinterpret_cast, const_cast, dynamic_cast), C-style casts and std::bit_cast.

2 March 2020updated 25 November 20261 min read

My short notes for casting in C++.

Static Cast

Converts between related types and checks at compile time that the conversion is allowed. Numeric conversions, void* back to a typed pointer and up/down casts in a class hierarchy all go here. There is no runtime check, so a wrong downcast compiles but is undefined behaviour.

double d = 3.7;
int i = static_cast<int>(d);          // 3

struct Base { virtual ~Base() = default; };
struct Derived : Base {};
Base* b = new Derived;
Derived* p = static_cast<Derived*>(b); // OK only because b really points to a Derived

Reinterpret Cast

Reinterprets the bits of a pointer (or integer) as an unrelated type. The compiler does not check if it makes sense. It can’t remove const or volatile qualifiers, that is the job of const_cast. Reading an object through a pointer of an unrelated type is usually undefined behaviour (strict aliasing), so I use it mostly for char*/std::byte* access and talking to low level APIs.

std::uint32_t value = 0x12345678;
auto bytes = reinterpret_cast<const unsigned char*>(&value); // reading bytes is allowed
std::uintptr_t addr = reinterpret_cast<std::uintptr_t>(&value);

Const Cast

Adds or removes const (and volatile). It is the only C++ cast that can do this. Removing const is fine to call an old API that takes char* but doesn’t modify it. Writing to an object that was originally declared const is undefined behaviour.

void legacy_print(char* s);

const std::string name = "okan";
legacy_print(const_cast<char*>(name.c_str())); // OK as long as legacy_print doesn't write

Dynamic Cast

Casts at runtime inside a polymorphic class hierarchy (the base class needs at least one virtual function). If the object is not of the target type it returns nullptr for pointers and throws std::bad_cast for references.

Base* b = new Base;
if (auto d = dynamic_cast<Derived*>(b)) {
    // b points to a Derived
} else {
    // not a Derived, d is nullptr
}

C-style cast

(int)d or int(d) tries const_cast, static_cast, static_cast + const_cast, reinterpret_cast and reinterpret_cast + const_cast in that order and takes the first one that works. That’s why it is hard to see what it really does, and I prefer the named casts.

std::bit_cast (C++20)

Update (2026): Since C++20, std::bit_cast in <bit> copies the object representation of one type into another type of the same size. It is the safe way to do type punning, for example looking at the bits of a float, instead of reinterpret_cast or a union.

#include <bit>
#include <cstdint>

float f = 1.0f;
auto bits = std::bit_cast<std::uint32_t>(f); // 0x3f800000