
C++中的虚表,虚指针用来实现多态,vTable来表示虚表,虚表中存放的是虚函数的地址
虚函数
在类中用virtual关键字修饰的函数就叫虚函数,vTable(虚表)是C++利用runtime来实现多态的工具,所以我们需要借助virtual关键字将函数代码地址存入vTable来躲开静态编译期
没有虚函数,即没有用到vTable的例子
#include <iostream>
#include <ctime>
using std::cout;
using std::endl;
struct Animal { void makeSound() { cout << "animal" << endl; } };
struct Cow : public Animal { void makeSound() { cout << "cow" << endl; } };
struct Pig : public Animal { void makeSound() { cout << "pig" << endl; } };
struct Donkey : public Animal { void makeSound() { cout << "donkey" << endl; } };
int main(int argc, const char * argv[])
{
srand((unsigned)time(0));
int count = 4;
while (count --) {
Animal *animal = nullptr;
switch (rand() % 3) {
case 0:
animal = new Cow;
break;
case 1:
animal = new Pig;
break;
case 2:
animal = new Donkey;
break;
}
animal->makeSound();
delete animal;
}
return 0;
}
上面程序的输出结果是
animal
animal
animal
animal
基类Animal的makeSound()方法没有使用Virtual修饰,静态编译时makeSound()实现就定了,调用makeSound()方法时,编译器发现这是Animal指针,就会直接jump到对应的代码段地址,那如果把Animal的makeSound()改为虚函数
struct Animal { virtual void makeSound() { cout << "animal" << endl; } };
输出结果就不一样了
cow
cow
pig
donkey
虚表
我们需要修改一下基类Animal的代码,不改变其他子类
struct Animal {
virtual void makeSound() { cout << "动物叫了" << endl; }
virtual void walk() {}
void sleep() {}
};
struct Cow : public Animal { void makeSound() { cout << "牛叫了" << endl; } };
struct Pig : public Animal { void makeSound() { cout << "猪叫了" << endl; } };
struct Donkey : public Animal { void makeSound() { cout << "驴叫了" << endl; } };
首先我们需要知道几个关键点:
- 函数只要有virtual,我们就需要把它添加进vTable。
- 每个类(而不是类实例)都有自己的虚表,因此vTable就变成了vTables。
- 虚表存放的位置一般存放在模块的常量段中,从始至终都只有一份。详情可在此参考
Animal、Cow、Pig、Donkey类都有自己的虚表,并且虚表里都有两个地址指针指向makeSound()和walk()的函数地址。一个指针4个字节,因此每个vTable的大小都是8个字节,如图:

他们的虚表中记录着不同函数的地址值。可以看到Cow、Pig、Donkey重写了makeSound()函数但是没有重写walk()函数。因此在调用makeSound()时,就会直接jump到自己实现的code Address。而调用walk()时,则会jump到Animal父类walk的Code Address
虚指针
现在我们已经知道虚表的数据结构了,那么我们在堆里实例化类对象时是怎么样调用到相应的函数的呢?这就要借助到虚指针了(vPointer)
虚指针是类实例对象指向虚表的指针,存在于对象头部,大小为4个字节,比如我们的Donkey类的实例化对象数据结构就如下:

我们修改main函数里的代码,如下
int main(int argc, const char * argv[])
{
int count = 2;
while (count --) {
Animal *animal = new Donkey;
animal->makeSound();
delete animal;
}
return 0;
}
我们在堆中生成了两个Donkey实例,运行结果如下:
然后我们再来看看堆里的结构,就变成了这样
