I see some strange code in our project like follows.I test it and get the right answer.But I think it is illegal,Can anyone explain this to me?
class Member
{
public:
Member():
a(0),b(1)
{}
int a;
int b;
};
// contains `Member` as its first member
class Container
{
public:
Container():
c(0),d(0)
{}
Member getMemb(){return fooObject;}
Member fooObject;
int c;
int d;
};
and how we use it:
int main()
{
auto ctain = new Container;
auto meb = (Member *)ctain; // here! I think this is illegal
cout << "a is " << meb->a << ", b is" << meb->b << endl;
return 0;
}
but I get the right answer, a is 0 and b is 1.Is this just a coincidence?I also noted that if fooObject
is not the first member, I will get a wrong answser.