宣告 virtual 函數會在類別中隱含加入指向虛函數表(vtable)的指標(vptr)。每個類別有一張靜態 vtable,存放虛函數位址。
struct A { long a; virtual void ABC(), BCD(); };
// 等價於
struct A { void (A::*vptr)(); long a; void ABC(), BCD(); A(); };
void (A::*A::vtable[])() = { &A::ABC, &A::BCD };
A::A() { vptr = vtable; }
呼叫 a.ABC() 實為 (a.*(a.vptr[0]))()。
多重繼承每個基底子物件有獨立 vptr。透過基底指標呼叫虛函數需調整 this 指標。編譯器產生 thunk(微調 this 偏移後轉呼叫真實函數)置入 vtable。
// E 繼承 B, C, D (皆繼承 A)
struct E {
void (E::*B_vptr)(); long B_a, b;
void (E::*C_vptr)(); long C_a, c;
void (E::*D_vptr)(); long D_a, d; long e;
void ABC() { e = 10; }
static void E_C_thunk_ABC() { this = (E*)((char*)this - 12); ABC(); }
static void E_D_thunk_ABC() { this = (E*)((char*)this - 24); ABC(); }
};
void (E::*E_C_vtable[])() = { E_C_thunk_ABC, E::BCD };
class Animal { public: virtual void Gnar() = 0; }; // 純虛,無定義
class Cat : public Animal { void Gnar() override { /* 貓叫 */ } };
=0 告訴編譯器「無定義」,嘗試實例化基底類別會編譯錯誤。Base::func() 明確呼叫)。