简体   繁体   中英

Member Function Call and the C++ Object Model

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,

  1. B::f() would be translated to void f(B *const)
  2. 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!

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_;

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