Reputation: 1608
Consider the below code that is designed to study how member functions calls are made and how it relates to C++'s object model:
struct A {
int a_;
};
struct B : A {
int b_;
void f();
};
void B::f() {
std::cout << "this\t" << std::hex << this << '\n';
}
struct C: B {
int c_;
};
int main()
{
C c;
C* pc = &c;
std::cout << "&c\t" << std::hex << pc << '\n';
pc->f();
return 0;
}
Based on the C++ object model, object c
will have the object layout:
-------
| a_ |
|------ |
| b_ |
|------ |
| c_ |
-------
And,
B::f()
would be translated to void f(B *const)
pc->f()
would be translated to void f(pc + offset(b_))
, where offset(b_)
represents the offset of sub-object B
in c
.So, based on the above observations, the output should be:
&c address_of_c
this address_of_c + sizeof(a_) = address_of_c + 4
But what I'm getting is the same address for both (I'm using g++ 9.2):
&c 0xffffcc0c
this 0xffffcc0c
I'm not clear as to why? Can someone please explain?
FYI: Bjarne Stroustrup has an article written about this; more specifically, you can refer to section 4.2 (page 373):
https://www.usenix.org/legacy/publications/compsystems/1989/fall_stroustrup.pdf
Thanks!
Upvotes: 1
Views: 56
Reputation: 311088
Class C inherits only one class B. So you have
struct B
^
|
|
struct C
When an object of the class C was created the sub-object of the class B was placed in the beginning of the memory allocated for the object of the class C.
Within the object of the class B there is a sub-object of the class A.
You can imagine the placement of an object of the class C the following way
struct B b;
int c_;
Upvotes: 1