Reputation: 3658
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;
}
Upvotes: 7
Views: 2916
Reputation: 31642
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?
(C1x §6.7.2.1.13: "A pointer to a structure object, suitably converted, points to its initial member ... and vice versa. There may be unnamed padding within as structure object, but not at its beginning.")
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++.
Upvotes: 12
Reputation: 35136
If you stand on the border of your country with a cup of coffee in your hand then your coordinates, the coordinates of the border and the coordinates of coffee cup will all have same value on a GPS device.
First child's first element happens to be at the starting address of the object. Names are for your own convenience computers work with memory addresses. You can name them whatever you want but memory layout depends on order and hierarchy of data members.
Upvotes: 3
Reputation: 3212
Because they're in the same place. The first element in struct A
is a struct B
, so they're actually in the same memory location (anything else in struct A
would then be put after b
).
Similarly, x
is the first bit of data in struct B
, so it's in the same position as the struct B
.
It's very important to note that this won't always be true. Things like virtual functions will cause stuff to move. It is true in this case because they're plain classes/structs.
Upvotes: 4