class A
{
int a1;
public:
virtual int A_virt1();
virtual int A_virt2();
};
class B
{
int b1;
int b2;
public:
virtual int B_virt1();
virtual int B_virt2();
};
class C: public A, public B
{
int c1;
public:
virtual int A_virt2();
virtual int B_virt2();
};
Thus, the layouts for our three classes will look like following (from MSVC):
class A size(8):
+---
0 | {vfptr}
4 | a1
+---
A's vftable:
0 | &A::A_virt1
4 | &A::A_virt2
class B size(12):
+---
0 | {vfptr}
4 | b1
8 | b2
+---
B's vftable:
0 | &B::B_virt1
4 | &B::B_virt2
class C size(24):
+---
| +--- (base class A)
0 | | {vfptr}
4 | | a1
| +---
| +--- (base class B)
8 | | {vfptr}
12 | | b1
16 | | b2
| +---
20 | c1
+---
C's vftable for A:
0 | &A::A_virt1
4 | &C::A_virt2
C's vftable for B:
0 | &B::B_virt1
4 | &C::B_virt2
Main Function :
A* a;
C c;
a = &c;
a->A_virt2(); // will call C::A_virt2() , that's fine because we have the address REWRITTEN in the vtable
// (it was first A::A_virt2 then it became C::A_virt2() )
But please explain (every bit) what is happening when I write this piece of code :
a->A::A_virt2(); // will call A::A_virt2()
How does it know if we don't have the address of A::A_virt2() in our vtable , where does it take from ?
Could you please explain a little bit more detailed.
I know if I write a->A_virt2() it will call C::A_virt2() because the pointer "*a" will go to subobject "A" in the "C" class and take that address from vtable of subobject "A".
You say "The function to call is known at compile time so no table lookup is needed. " , which part of "C" class object grabs the pointer "*a", for the A::A_virt2() function (What's happening under the courtains?).
If my question is vague, and I should read something before asking please give me the source :).