Usiten Usiten - 1 month ago 5
C++ Question

In-class struct, how does "this" work?

As stated, how does the

this
pointer act when called in a struct defined in a class ?
Let's say I have the following piece of code:

class A {
public:
struct {
void bar() { std::cout << this << std::endl; }
} foo;
};

int main() {
A a; a.foo.bar();
std::cout << &a << std::endl;
std::cout << &a.foo << std::endl;
}


That generate this output:

0x62fe9f
0x62fe9f
0x62fe9f


a.foo
share the same address with
a
, how could one access to the
this
pointer of
foo
?

Using
this->foo
raise an error:

test.cpp:20:23: error: 'struct A::<anonymous>' has no member named 'foo'

Answer

The address is mostly just where the memory if the object "starts". How much to offset is needed members is then defined by the class definition.

So class A "starts" at 0x62fe9f.

At the beginning of class A is the member foo so because there is nothing in front of it it has also address 0x62fe9f etc.

When you change the class to

class A {
public:
    int i;
    struct {
        void bar() {  std::cout << this << std::endl;  }
    } foo;
};

You shloud see &a.i and &a having the same address and &a.foo should be &a + sizeof(int)

(Note: It may be more than sizeof(int) and in other cases also different because how padding is set. This is just a simple example. You should not rely on this in real code)

Comments