This is modification of question and code presented in this link: C++ multiple inheritance and vtables. I understood from this link how vptr & vtable are setup.
My question is how does, bp->OutB() retrieves value of int a, which is member of classA. I thought we pass this pointer to this method which looks at B part of class C. Specifically, Memory layout of classC assuming 32 bit.
&obj.
+0: vptr( pointer to virtual method table of classC( for classA).
+4: value of a.
+8: vptr( pointer to virtual method table of classC( for classB).
+12: value of b.
+16: value of c.
My questions is, we pass &obj+8 as this pointer to when we execute: bp->OutB(), but how does it end up retrieving member: int a of class A in that case.
#include <iostream>
using namespace std;
class A
{
public:
virtual void OutA() = 0;
int a;
};
class B
{
public:
virtual void OutB() = 0;
int b;
};
class C : public A, public B
{
void OutA();
void OutB();
int c;
};
void C::OutA()
{
cout << "Out A " << endl;
}
void C::OutB()
{
cout << "Out B " << " a is: " << a << endl;
}
int main()
{
C obj;
obj.a = 10;
obj.b = 20;
obj.c = 30;
obj.OutA();
obj.OutB();
A* ap = (A*)&obj;
B* bp = (B*)&obj;
ap->OutA();
bp->OutB();
return 0;
}