vtable
Vtable
虚表。
每一个有虚函数的类都有这样一个东西。
它实际上记录了本类中所有虚函数的函数指针,也就是说是个函数指针数组的起始位置。
比如virtual void TheSecondFun()记录在数组的第二个元素,当一个该类的对象实例调用TheSecondFun时就根据对应关系把第二个函数指针取出来,再去执行该函数,这种行为叫晚绑定,也就是说在运行时才知道调用的函数是什么样子的,而不是在编译阶段就确定的早绑定。
例:
实现多态:
class a
{
public:
virtual void fun1();
vitrual void fun2();
private:
int i;
}
class b : public a
{
public:
virtual void fun2();
virtual void fun3();
private:
int j;
}
则class a 的内存layout为(win32 platform)
begin of layout of class a
vtable pointer (pointer to vtable of class a see below) (4 bytes)
int i (4 bytes)
end of layout of class a
vtable of class a
begin of vtable of class a
start address of a::fun1 (4 bytes)
start address of a::fun2 (4 bytes)
end of vtable of class a
class b 的内存layout为(win32 platform)
begin of layout of class b
vtable pointer (pointer to vtable of class b see below) (4 bytes)
int i (4 bytes)
int j (4 bytes)
end of layout of class b
vtable of class b
begin of vtable of class b
start address of a::fun1 (4 bytes)
start address of b::fun2 (4 bytes)
start address of b::func3 (4 bytes)
end of vtable of class b
所以才有
a* p = new b;
p->fun2() 调 b::fun2()