Suppose there are two struct A and B. They have a common struct C.
I would like to know if it is safe to call reinterpret_cast to A or B to C.
if not, is there any way to do so without any performance impact?
struct C
{
string m_c1;
int32_t m_c2;
double m_c3;
string m_c4;
};
struct A
{
C m_a1;
string m_a2;
int32_t m_a3;
};
struct B
{
C m_b1;
string m_b2;
int32_t m_b3;
double m_b4;
};
int main(int argc,char *argv[])
{
A a;
a.m_a1.m_c1="A";
a.m_a1.m_c4="AA";
B b;
b.m_b1.m_c1="B";
b.m_b1.m_c4="BB";
C* pc = reinterpret_cast<C*>(&a);
cout << pc->m_c1 << " " << pc->m_c4 << endl;
pc = reinterpret_cast<C*>(&b);
cout << pc->m_c1 << " " << pc->m_c4 << endl;
return 1;
}
Why dont you inherit both A,B from C and then use
static_castinstead? Should be safer/cleaner.Indeed in your case, you shouldnt need a cast at all, you should be able to assign A or B ptrs to a
C*