简体   繁体   中英

Why do class members have the same address as their object?

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?

(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++.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM