1

I know base offset adjustment will happen in this situation

class Mother {
 public:
  virtual void MotherMethod() {}
  int mother_data;
};

class Father {
 public:
  virtual void FatherMethod() {}
  int father_data;
};

class Child : public Mother, public Father {
 public:
  virtual void ChildMethod() {}
  int child_data;
};
Father *f = new Child;

During compilation, this code is equivalent to

Child *tmp = new Child;
Father *f = tmp ? tmp + sizeof(Mother) : 0;

My question is how this offset is determined in the compilation phase? for example, in the following case

void fun(Father* f) {
    // do something
}

we don't know what object the pointer will receive, how is it possible to determine whether or how much offset adjustment is needed during compilation.

I hope someone can answer my doubts, Thank you very much!

x f
  • 63
  • 4
  • 2
    https://stackoverflow.com/questions/2680369/how-is-inheritance-implemented-at-the-memory-level https://stackoverflow.com/questions/42467884/how-does-c-compiler-handle-member-variable-memory-offset-in-the-case-of-multip https://medium.com/geekculture/c-inheritance-memory-model-eac9eb9c56b5 – KamilCuk Feb 24 '22 at 13:41

1 Answers1

2

The caller of a function knows exactly what types are involved and does the necessary adjustments.

That is,

Child c;
fun(&c);

behaves exactly the same as

Child c;
fun(static_cast<Father*>(&c));

but the conversion is implicit.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82