C++ When should we prefer to use a two chained static_cast over reinterpret_cast

c++, casting, reinterpret-cast, static-cast

Solution

`reinterpret_cast` should be a huge flashing symbol that says THIS LOOKS CRAZY BUT I KNOW WHAT I'M DOING. Don't use it just out of laziness.

`reinterpret_cast` means "treat these bits as ..." Chained static casts are not the same because they may modify their targets according to the inheritence lattice.

struct A {
    int x;
};

struct B {
    int y;
};

struct C : A, B {
    int z;
};

C c;
A * a = &c;

int main () {
    assert (reinterpret_cast <B *> (a) != static_cast <B *> (static_cast <C *> (a)));
}

If you are not 100% sure that `a` points to a `b`, use `dynamic_cast` which will search for the above solution (albeit with a runtime cost). Bear in mind that this may return NULL or throw on failure.

I'm trying to think of times when I've actually used `reinterpret_cast`, there are really only two:

- when a function is zipping/encrypting an arbitrary buffer and I want to use a `const char *` to traverse it

- `if(*reinterpret_cast<uint32_t*>(array_of_4_bytes_A) < *reinterpret_cast<uint32_t*>(array_of_4_bytes_B)` or somesuch. Lines like this invite scrutiny and demand comments.

Otherwise if you have a `A*` which is really a `B*` then you probably want a union.

Problem

First of all, this is not a duplicate of Why do we have reinterpret_cast in C++ when two chained static_cast can do it's job?. I know situations where we cannot use even two chained `static_cast` to achieve that, what `reinterpret_cast` does. But is there any situation where I should prefer a two chained `static_cast` over a simple and more readable `reinterpret_cast`?

Original source

Related problems