Given the following conditions:
struct A
{
int a;
};
struct B
{
int b;
};
int main()
{
A a {1};
A* p = &a;
Does casting with static_cast
and with reinterpret_cast
via void*
give the same result? I.e is there any difference between the following expressions?
static_cast <A*> ( static_cast <void*> (p) );
reinterpret_cast <A*> ( reinterpret_cast <void*> (p) );
What if we cast pointer to one class to pointer to another class with static_cast
and with reinterpret_cast
? Is there any difference between these two operators? Are the following expressions the same?
static_cast <B*> ( static_cast <void*> (p) );
reinterpret_cast <B*> ( reinterpret_cast <void*> (p) );
reinterpret_cast <B*> ( p );
Can I use B*
pointer after this to access b
member?
p
toB*
is not always equivalent to casting tovoid*
first -- it just is for OP's examples. IfA
andB
were hierarchically related, the pointer value can change as part of the cast. Plus, casting fromA -> void -> B
AFAIK is always undefined behavior to dereference, whereasA -> B
can be legal provided two types are layout-compatible – Brachio