Reputation: 15
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'
Upvotes: 0
Views: 106
Reputation: 5370
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)
Upvotes: 6
Reputation: 140609
Possibly this modified version of your program, and its output, will be enlightening.
#include <iostream>
using std::cout;
class A {
public:
int data;
struct {
int data;
void bar()
{
cout << this << '\n';
cout << &this->data << '\n';
}
} foo;
void bar()
{
cout << this << '\n';
cout << &this->data << '\n';
cout << &this->foo << '\n';
}
};
int main(void)
{
A a;
cout << &a << '\n';
a.bar();
a.foo.bar();
}
Upvotes: 3