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
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 (a) != static_cast (static_cast (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:
const char * to traverse itif(*reinterpret_cast(array_of_4_bytes_A) < *reinterpret_cast(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.