Consider the following code
class B1 {
public:
void f0() {}
virtual void f1() {}
int int_in_b1;
};
class B2 {
public:
virtual void f2() {}
int int_in_b2;
};
class D : public B1, public B2 {
public:
void d() {}
void f2() {int temp=int_in_b1;} // override B2::f2()
int int_in_d;
};
and the following memory layout for the object d:
d:
+0: pointer to virtual method table of D (for B1)
+4: value of int_in_b1
+8: pointer to virtual method table of D (for B2)
+12: value of int_in_b2
+16: value of int_in_d
Total size: 20 Bytes.
virtual method table of D (for B1):
+0: B1::f1() // B1::f1() is not overridden
virtual method table of D (for B2):
+0: D::f2() // B2::f2() is overridden by D::f2()
D *d = new D();
d->f2();
When d->f2();
is invoked, D::f2
needs access to data from B1
, but modified this pointer
(*(*(d[+8]/*pointer to virtual method table of D (for B2)*/)[0]))(d+8) /* Call d->f2() */
is passed to D::f2
, then how is D::f2
able to access it?
The code is taken(and modified) from :https://en.wikipedia.org/wiki/Virtual_method_table#Multiple_inheritance_and_thunks
Your case is actually too simple: The compiler can know that you have a pointer to a D
object, so it can perform the lookup from the right table, passing the unmodified this
pointer to the f2()
implementation.
The interesting case is, when you have a pointer to B2
:
B2* myD = new D();
myD->f2();
Now we start with an adjusted base pointer, and need to find the this
pointer for the whole object. One way to achieve that would be to store an offset alongside the function pointer that is used to produce a valid this
pointer from the B2
pointer used to access the vtable.
Thus, in your case, the code might implicitly be compiled like this
D* myD = new D();
((B2*)myD)->f2();
adjusting the pointer two times (once deriving the B2*
from the D*
, then the inverse using the offset from the vtable). Your compiler may be clever enough to avoid this, though.
In any case, this is firmly within the field of implementation. Your compiler can do anything, as long as it behaves the way the standard specifies.