Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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;
}
like image 886
user103214 Avatar asked Oct 21 '11 04:10

user103214


1 Answers

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

like image 128
Steve Avatar answered Sep 20 '22 17:09

Steve