虚函数表的意义
虚函数表是用于实现动态绑定的一种机制。
动态绑定
动态绑定用于确定该调用的函数,用于支持多态,如:
#include <iostream>
class B
{
public:
virtual void bar();
virtual void qux();
};
void B::bar()
{
std::cout << "This is B's implementation of bar" << std::endl;
}
void B::qux()
{
std::cout << "This is B's implementation of qux" << std::endl;
}
class C : public B
{
public:
void bar() override;
};
void C::bar()
{
std::cout << "This is C's implementation of bar" << std::endl;
}
B* b = new C();
b->bar();
类、虚函数指针以及虚函数表的关系
当类继承定义了虚函数的父类,则子类会继承虚函数表以及虚函数指针。
-------
|class B|
-------
vpointer -----> Vtable of B
bar -------------------
qux -------------- |
| |
| |
| B::bar()
|- B::qux() ---
C::bar() |
------- | |
|class C| | |
------- | |
vpointer ----> Vtable of C | |
bar --------------------| |
qux ---------------------------
参考
https://pabloariasal.github.io/2017/06/10/understanding-virtual-tables/