轉自http://blog.csdn.net/pathuang68/article/details/4101981
內容概要:
滿足下面2個條件時,
1. 父類有虛函數,子類也有虛函數,且子類的虛函數重寫或覆蓋了父類的虛函數
2. 非虛繼承
類對象之內存佈局
前篇:http://blog.csdn.net/pathuang68/archive/2009/04/23/4101979.aspx
在前面的例子中,恢復原來的兩個虛函數vfBase_1()和vfBase_2(),同時在Derived類中重寫基類的虛函數vfBase_1(),Base類和Derived類之間的關係如下圖:
整個代碼如下:
#include <iostream>
using namespace std;
class Base
{
public:
int m_base;
inline virtual void vfBase_1()
{
cout << "This is in Base::vfBase_1()" << endl;
}
inline virtual void vfBase_2()
{
cout << "This is in Base::vfBase_2()" << endl;
}
};
class Derived : public Base
{
public:
int m_derived;
inline virtual void vfDerived()
{
cout << "This is in Derived::vfDerived()" << endl;
}
inline void vfBase_1()
{
cout << "This is in Derived::vfBase_1()" << 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 Base object = \t" << sizeof(Derived) << endl;
cout << endl;
int i = 0;
while(virtualFunctionPointer(&d, i))
{
VFun pVF = virtualFunctionPointer(&d, i++);
pVF();
}
return 0;
}
運行結果如下:
Derived 對象的memory layout圖解如下:
因爲Derived類中重寫了虛函數vfBase_1(),所以Derived::vfBase_1()就取代了Base::vfBase_1()的位置,位於虛函數表的開始處。而Base::vfBase_1()就不會再在Derived的虛函數表中出現了。