轉自http://blog.csdn.net/pathuang68/article/details/4101999
內容概要:
滿足下面3個條件時,
1. 父類有虛函數,子類也有虛函數,且子類的虛函數重寫或覆蓋了父類的虛函數
2. 非虛繼承
3. 多重繼承
類對象之內存佈局
前篇: http://blog.csdn.net/pathuang68/archive/2009/04/23/4101981.aspx
多重繼承,派生類不重寫基類中的虛函數。
假定各類之間的關係如下圖:
代碼如下:
#include <iostream>
using namespace std;
class Base1
{
public:
int m_base1;
inline virtual void vfBase1_1()
{
cout << "This is in Base1::vfBase1_1()" << endl;
}
inline virtual void vfBase1_2()
{
cout << "This is in Base1::vfBase1_2()" << endl;
}
};
class Base2
{
public:
int m_base2;
inline virtual void vfBase2_1()
{
cout << "This is in Base2::vfBase2_1()" << endl;
}
inline virtual void vfBase2_2()
{
cout << "This is in Base2::vfBase2_2()" << endl;
}
};
class Base3
{
public:
int m_Base3;
inline virtual void vfBase3_1()
{
cout << "This is in Base3::vfBase3_1()" << endl;
}
inline virtual void vfBase3_2()
{
cout << "This is in Base3::vfBase3_2()" << endl;
}
};
class Derived : public Base1, public Base2, public Base3
{
public:
int m_derived;
inline virtual void fd()
{
cout << "This is in Derived::fd()" << endl;
}
};
typedef void (*VFun)(void);
template<typename T>
VFun virtualFunctionPointer(T* b, int i)
{
return (VFun)(*((int*)(*(int*)b) + i));
}
int main(void)
{
Derived d;
cout << "The size of Derived object = /t" << sizeof(Derived) << endl;
cout << endl;
cout << "1st virtual function table: " << endl;
int i = 0;
while(virtualFunctionPointer(&d, i))
{
VFun pVF = virtualFunctionPointer(&d, i++);
pVF();
}
cout << endl;
cout << "2nd virtual function table: " << endl;
i = 0;
int* tmp = ((int*)&d) + 2;
while(virtualFunctionPointer(tmp, i))
{
VFun pVF = virtualFunctionPointer(tmp, i++);
pVF();
}
cout << endl;
cout << "3rd virtual function table: " << endl;
i = 0;
tmp = ((int*)&d) + 4;
while(virtualFunctionPointer(tmp, i))
{
VFun pVF = virtualFunctionPointer(tmp, i++);
pVF();
}
return 0;
}
運行結果如下:
Derived對象之memory layout如下:
由上面的分析可知:
其一:有三個虛函數表
其二:在Derived類中定義的虛函數Derived::vfDerived()附加在一個虛函數表的最後