So going back to basics, I’m trying to wrap my head around vtables and whatnot. In the following example, if I were to, say, pass a B* to some function, how does that function know to call the methods in the vtable of the C object instead of the methods from the vtable of A? Are there two, separate VTables that are passed to that object? Are interface pointers really just vtables (since interfaces, IIRC, cannot contain property declarations)?
What I’m trying to say is, up until I actually tried this code, I was under the assumption you couldn’t inherit off of more than one interface/class at a time (and that all of the interfaces had to be linear, so to speak) so that the vtable built onto itself.
If my idea of how vtables worked was correct (which I now know it is not), then passing a B* and called B::OutB() would have called A:OutA() instead (which is obviously not the case).
Can someone shed some light?
// Includes
#include <windows.h>
#include <iostream>
interface A
{
public:
virtual void OutA() = 0;
};
interface B
{
public:
virtual void OutB() = 0;
};
class C : public A, public B
{
public:
void OutA();
void OutB();
};
void C::OutA()
{
printf("Out A\n");
}
void C::OutB()
{
printf("Out B\n");
}
int main()
{
C obj;
obj.OutA();
obj.OutB();
A* ap = (A*)&obj;
B* bp = (B*)&obj;
ap->OutA();
bp->OutB();
system("pause");
// Return
return 0;
}
outputs (as expected):
Out A
Out B
Out A
Out B
I have no idea what an
interfaceis, because:interfaceis not a C++ keyword;But if you were writing C++ and
AandBwere classes, thenCwould contain two subobjects:AandB, and each of these subobject would have its own vtable pointer.When compiling C++ to C, we could have:
See http://ideone.com/TioyX
Output: