In the following cases, each member has a different name or entity so why are their addresses the same?
struct B { int x; };
struct A { B b; };
int main()
{
A obj;
cout << &obj.b.x << endl;
cout << &obj.b << endl;
cout << &obj << endl;
}
Because a pointer to a struct always points to it’s first member (as the struct is laid out sequentially).
In C, does a pointer to a structure always point to its first member?
NOTE: mange points out, rightfully so, that if you start adding virtual functions to your struct, C++ implements this by tacking the vtable at the start of your struct… which makes my statement (which is true for C) incorrect when you talk about everything you could possibly do with ‘structs’ in C++.