c++ Multiple Inheritance - Compiler modifying my pointers
Posted
by
Bob
on Stack Overflow
See other posts from Stack Overflow
or by Bob
Published on 2012-10-20T04:37:56Z
Indexed on
2012/10/20
5:01 UTC
Read the original article
Hit count: 130
If I run the following code, I get different addresses printed. Why?
class Base1 {
int x;
};
class Base2 {
int y;
};
class Derived : public Base1, public Base2 {
};
union U {
Base2* b;
Derived* d;
U(Base2* b2) : b(b) {}
};
int main()
{
Derived* d = new Derived;
cout << d << "\n";
cout << U(d).d << "\n";
return 0;
}
Even more fun is if you repeatedly go in and out of the union the address keeps incrementing by 4, like this
int main()
{
Derived* d = new Derived;
cout << d << "\n";
d = U(d).d;
cout << d << "\n";
d = U(d).d;
cout << d << "\n";
return 0;
}
If the union is modified like this, then the problem goes away
union U {
void* v;
Base2* b;
Derived* d;
U(void* v) : v(v) {}
};
Also, if either base class is made empty, the problem goes away. Is this a compiler bug? I want it to leave my pointers the hell alone.
© Stack Overflow or respective owner