skip to content

Casts and Conversions

static_cast, const_cast and reinterpret_cast each permit one kind of conversion, and a C-style cast tries them all. Interviewers ask which cast a line needs and why.

on this pageshow

explore

questions

5

In C++, what does each of static_cast, const_cast and reinterpret_cast permit, and which one restores a callback's void* user data?

level: juniorimportance: must knowfreq 72%

answer

  1. one cast, one family of conversions
  2. inverse of the implicit T* to void*
  3. qualifiers only
  4. addresses and integers, never values

basics

~10 s

static_cast performs conversions the compiler understands, including void* back to the original T*; const_cast only adds or removes const and volatile; reinterpret_cast reinterprets pointers and integers. static_cast restores void* user data.

solid answer

~40 s

Each named cast permits one family of conversions and rejects the rest. `static_cast` does conversions the compiler can reason about: numeric ones, hierarchy casts without a run-time check, explicit constructors, and `void*` back to an object pointer, but it never removes `const`. `const_cast` changes only `const` and `volatile` qualifiers. `reinterpret_cast` converts between unrelated pointer types, pointers and integers, and function pointer types; it never converts a value such as a `float`, and it cannot drop `const`. For a C callback's `void* user`, `static_cast<Session*>(user)` is the right cast: it is the inverse of the implicit `Session*` to `void*` conversion and gives back the original pointer, provided you cast to exactly the type that was stored.

code

cpp · 27 lines
cpp
#include <cstdio>

// Legacy C plugin interface
extern "C" {
typedef void (*on_data_fn)(void* user, const char* buf, int len);
void register_callback(on_data_fn fn, void* user) { fn(user, "PING", 4); }
void legacy_log(char* msg) { std::puts(msg); }   // never writes, but takes char*
}

struct Session {
    int packets = 0;
    void on_data(const char* buf, int len) {
        ++packets;
        legacy_log(const_cast<char*>(buf));      // drops const only; legacy_log just reads
        std::printf("%d bytes, packet %d\n", len, packets);
    }
};

extern "C" void trampoline(void* user, const char* buf, int len) {
    auto* self = static_cast<Session*>(user);    // void* back to the stored Session*
    self->on_data(buf, len);
}

int main() {
    Session s;
    register_callback(&trampoline, &s);          // Session* to void* is implicit
}

go deeper

for a junior

Recall the job of each cast: static_cast for ordinary conversions and void* back to T*, const_cast for qualifiers, reinterpret_cast for addresses.

for a middle

Explain why static_cast is the right inverse of an implicit T* to void* conversion and which conversions each named cast refuses.

for a senior

In C interop code, insist that void* user data is cast back to exactly the stored type, and treat each reinterpret_cast as needing a justification.

for a principal

Make named casts the only allowed form in the codebase, enforced by -Wold-style-cast as an error, with reinterpret_cast and const_cast flagged for review.

## Why C++ splits casting into named operators A C cast `(T)x` can mean several very different things: a value conversion, dropping `const`, or reinterpreting an address as another type. C++ keeps that syntax for compatibility, but adds **named cast operators**, each allowed to perform only one family of conversions. Writing the name says which family you meant, and the compiler rejects the line if the conversion falls outside it. There are four: `static_cast`, `const_cast`, `reinterpret_cast` and `dynamic_cast`. The last one checks a polymorphic type at run time and belongs with RTTI; this answer covers the other three. ## `static_cast`: conversions the type system can reason about `static_cast<T>(e)` performs conversions whose meaning the compiler knows from the types alone: - numeric conversions spelled out on purpose: `static_cast<int>(2.9)` is `2`, `static_cast<double>(n) / d` forces floating division; - **`void*` back to an object pointer**: the inverse of the implicit `T*` to `void*` conversion; - up and down a class hierarchy without a run-time check (`Base*` to `Derived*` is your promise that the object really is a `Derived`); - calls to a constructor or a conversion function, including an `explicit` one; - enumerations to and from integers, and anything to `void` to discard a value. It refuses to remove `const`: `static_cast<char*>(msg)` with `const char* msg` fails with "static_cast from 'const char *' to 'char *' is not allowed". ## `const_cast`: only qualifiers `const_cast<T>(e)` adds or removes `const` and `volatile` on a pointer or reference and changes **nothing else**. Its legitimate use is calling a legacy API that is not const-correct but does not write, such as `void legacy_log(char* msg)`. Whether writing through the result is allowed depends on the object, not on the cast; that is its own interview question. ## `reinterpret_cast`: addresses and bit-level views `reinterpret_cast<T>(e)` converts between **pointer and reference types that are unrelated**, between pointers and integers (`std::uintptr_t`), and between function pointer types. The draft lists its conversions exhaustively and adds "No other conversion can be performed explicitly using reinterpret_cast". It never converts a value such as a `float` to an `int` (`reinterpret_cast<std::uint32_t>(1.0f)` does not compile), and it cannot cast away `const` ("casts away qualifiers"). Converting a pointer to another object pointer type and back gives the original pointer, provided the intermediate type's alignment is no stricter; *using* the intermediate pointer to read the object is governed by the aliasing rule, covered with type punning. | Cast | Changes the type how | Typical legal use | |---|---|---| | `static_cast` | a conversion the compiler understands | `void*` to `Session*`, `double` to `int` | | `const_cast` | qualifiers only | pass `const char*` to a read-only `char*` API | | `reinterpret_cast` | reinterprets addresses | pointer to `std::uintptr_t`, function pointer types | ## The plugin callback A C plugin interface typically takes a function pointer and an opaque `void* user`. Passing `&session` as `user` converts `Session*` to `void*` implicitly; inside the callback, `static_cast<Session*>(user)` restores it. The standard guarantees the round trip: when a `void*` that came from a `T*` is converted back with `static_cast<T*>`, the result points to the original object. `reinterpret_cast<Session*>(user)` also works, because between object pointers it is defined as going through `void*` with `static_cast`, but it announces a riskier conversion than the one taking place, so reviewers prefer `static_cast` here. The guarantee covers **exactly the type that was stored**. If the plugin stored a `Derived*` and the callback casts the `void*` to a base class pointer, no base adjustment happens, which matters as soon as multiple inheritance is involved. ## Mistakes worth naming 1. Using a C-style cast in the callback: it compiles for every one of these cases, so a wrong conversion is not reported. 2. Using `reinterpret_cast` where `static_cast` would do: it widens what the compiler accepts without making the code safer. 3. Using `const_cast` to silence an error from an API that really writes: the write may then hit an object defined `const`. 4. Casting the `void*` to a different type than the one stored, typically a base class. 5. Treating "it compiled" as proof: every one of these casts compiles in the wrong place too; only the named form narrows what the compiler will accept. A practical bonus of the named forms is that they are **searchable**: grepping a ported plugin for `reinterpret_cast` and `const_cast` lists exactly the lines that need a second look, which no search for `(` can do.

  • Why not just use `reinterpret_cast<Session*>(user)` in the callback?
    Between object pointer types the standard defines `reinterpret_cast` as a `static_cast` through `void*`, so the result is the same here. The cost is in review: `reinterpret_cast` also accepts integer-to-pointer and unrelated-pointer conversions, so it hides mistakes that `static_cast` would reject, and it signals danger where there is none.
  • What goes wrong if the plugin stored a `Plugin*` and the callback does `static_cast<Listener*>(user)` for a base class `Listener`?
    A `void*` carries no type, so the conversion produces a `Listener*` with the same address the `Plugin*` had. With multiple inheritance the `Listener` subobject may sit at a different address, so the pointer is wrong and using it is undefined behaviour. Cast back to `Plugin*` first, then convert to `Listener*`.

  • static_cast can remove const if the target type is non-const.
  • reinterpret_cast<int>(3.7f) converts the float to an integer value.
  • const_cast creates a modifiable copy of the object.
  • A void* can be cast to any base class of the stored object safely.
  • Named casts are just verbose spellings of the same C cast.
open as a page

In C++, what does `explicit` block on a constructor and on `operator bool`, and where does `explicit operator bool` still convert?

level: middleimportance: must knowfreq 60%

basics

~20 s

An explicit constructor is not used for copy-initialization or implicit conversions, only for direct-initialization and casts. An explicit operator bool converts only in explicit casts and contextual conversions such as if conditions, !, && and ||.

open as a page

In C++, when is writing through a pointer obtained with `const_cast` well-defined, and when is it undefined behaviour?

level: middleimportance: should knowfreq 52%

basics

~20 s

Writing through a const_cast result is defined only when the object itself was not created const; const_cast merely removes const from the access path. Modifying an object defined const, such as a const variable or a string literal, is undefined behaviour.

open as a page

What does a C-style cast `(T)expr` actually do in C++, and why can it silently become a reinterpret_cast?

level: middleimportance: should knowfreq 55%

basics

~10 s

A C-style cast tries const_cast, static_cast, static_cast plus const_cast, reinterpret_cast, then reinterpret_cast plus const_cast, and uses the first that applies. When no static_cast exists, it quietly reinterprets the address instead of failing.

open as a page

In C++20, why does `std::bit_cast<std::uint32_t>(gain)` work where `reinterpret_cast<std::uint32_t>(gain)` does not compile, and what does bit_cast require?

level: seniorimportance: should knowfreq 45%

basics

~10 s

reinterpret_cast converts addresses, pointers and integers, never a float value, so the value form is ill-formed. std::bit_cast (C++20) copies the bits into a new object and needs equal sizes and trivially copyable types.

open as a page