Let's assume that A
and B
are two classes (or structures) having no inheritance relationships (thus, object slicing cannot work). I also have an object b
of the type B
. I would like to interpret its binary value as a value of type A
:
A a = b;
I could use reinterpret_cast
, but I would need to use pointers:
A a = reinterpret_cast<A>(b); // error: invalid cast
A a = *reinterpret_cast<A *>(&b); // correct [EDIT: see *footnote]
Is there a more compact way (without pointers) that does the same? (Including the case where sizeof(A) != sizeof(B)
)
Example of code that works using pointers: [EDIT: see *footnote]
#include <iostream>
using namespace std;
struct C {
int i;
string s;
};
struct S {
unsigned char data[sizeof(C)];
};
int main() {
C c;
c.i = 4;
c.s = "this is a string";
S s = *reinterpret_cast<S *>(&c);
C s1 = *reinterpret_cast<C *>(&s);
cout << s1.i << " " << s1.s << endl;
cout << reinterpret_cast<C *>(&s)->i << endl;
return 0;
}
*footnote: It worked when I tried it, but it is actually an undefined behavior (which means that it may work or not) - see comments below
(&c);` Please also read the following to see why UB should be avoided especially when combined with modern compiler optimisations: http://en.cppreference.com/w/cpp/language/ub– Richard Critten Jun 17 '17 at 13:22