To implement virtual functions, C++ uses a special form of late binding known as the virtual table. The virtual table is a lookup table of functions used to resolve function calls in a dynamic/late binding manner. The virtual table sometimes goes by other names, such as “vtable”, “virtual function table”, “virtual method table”, or “dispatch table”.

Because knowing how the virtual table works is not necessary to use virtual functions, this section can be considered optional reading.

The virtual table is actually quite simple, though it’s a little complex to describe in words. First, every class that uses virtual functions (or is derived from a class that uses virtual functions) is given its own virtual table. This table is simply a static array that the compiler sets up at compile time. A virtual table contains one entry for each virtual function that can be called by objects of the class. Each entry in this table is simply a function pointer that points to the most-derived function accessible by that class.

Second, the compiler also adds a hidden pointer to the base class, which we will call *__vptr. *__vptr is set (automatically) when a class instance is created so that it points to the virtual table for that class. Unlike the *this pointer, which is actually a function parameter used by the compiler to resolve self-references, *__vptr is a real pointer. Consequently, it makes each class object allocated bigger by the size of one pointer. It also means that *__vptr is inherited by derived classes, which is important.

By now, you’re probably confused as to how these things all fit together, so let’s take a look at a simple example:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Base
{
public:
    virtual void function1() {};
    virtual void function2() {};
};
 
class D1: public Base
{
public:
    virtual void function1() {};
};
 
class D2: public Base
{
public:
    virtual void function2() {};
};

Because there are 3 classes here, the compiler will set up 3 virtual tables: one for Base, one for D1, and one for D2.

The compiler also adds a hidden pointer to the most base class that uses virtual functions. Although the compiler does this automatically, we’ll put it in the next example just to show where it’s added:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Base
{
public:
    FunctionPointer *__vptr;
    virtual void function1() {};
    virtual void function2() {};
};
 
class D1: public Base
{
public:
    virtual void function1() {};
};
 
class D2: public Base
{
public:
    virtual void function2() {};
};

When a class object is created, *__vptr is set to point to the virtual table for that class. For example, when a object of type Base is created, *__vptr is set to point to the virtual table for Base. When objects of type D1 or D2 are constructed, *__vptr is set to point to the virtual table for D1 or D2 respectively.

Now, let’s talk about how these virtual tables are filled out. Because there are only two virtual functions here, each virtual table will have two entries (one for function1(), and one for function2()). Remember that when these virtual tables are filled out, each entry is filled out with the most-derived function an object of that class type can call.

The virtual table for Base objects is simple. An object of type Base can only access the members of Base. Base has no access to D1 or D2 functions. Consequently, the entry for function1 points to Base::function1(), and the entry for function2 points to Base::function2().

The virtual table for D1 is slightly more complex. An object of type D1 can access members of both D1 and Base. However, D1 has overridden function1(), making D1::function1() more derived than Base::function1(). Consequently, the entry for function1 points to D1::function1(). D1 hasn’t overridden function2(), so the entry for function2 will point to Base::function2().

The virtual table for D2 is similar to D1, except the entry for function1 points to Base::function1(), and the entry for function2 points to D2::function2().

Here’s a picture of this graphically:

Although this diagram is kind of crazy looking, it’s really quite simple: the *__vptr in each class points to the virtual table for that class. The entries in the virtual table point to the most-derived version of the function objects of that class are allowed to call.

So consider what happens when we create an object of type D1:

 
1
2
3
4
int main()
{
    D1 d1;
}

Because d1 is a D1 object, d1 has its *__vptr set to the D1 virtual table.

Now, let’s set a base pointer to D1:

 
1
2
3
4
5
int main()
{
    D1 d1;
    Base *dPtr = &d1;
}

Note that because dPtr is a base pointer, it only points to the Base portion of d1. However, also note that *__vptr is in the Base portion of the class, so dPtr has access to this pointer. Finally, note that dPtr->__vptr points to the D1 virtual table! Consequently, even though dPtr is of type Base, it still has access to D1’s virtual table (through __vptr).

So what happens when we try to call dPtr->function1()?

 
1
2
3
4
5
6
int main()
{
    D1 d1;
    Base *dPtr = &d1;
    dPtr->function1();
}

First, the program recognizes that function1() is a virtual function. Second, the program uses dPtr->__vptr to get to D1’s virtual table. Third, it looks up which version of function1() to call in D1’s virtual table. This has been set to D1::function1(). Therefore, dPtr->function1() resolves to D1::function1()!

Now, you might be saying, “But what if Base really pointed to a Base object instead of a D1 object. Would it still call D1::function1()?”. The answer is no.

 
1
2
3
4
5
6
int main()
{
    Base b;
    Base *bPtr = &b;
    bPtr->function1();
}

In this case, when b is created, __vptr points to Base’s virtual table, not D1’s virtual table. Consequently, bPtr->__vptr will also be pointing to Base’s virtual table. Base’s virtual table entry for function1() points to Base::function1(). Thus, bPtr->function1() resolves to Base::function1(), which is the most-derived version of function1() that a Base object should be able to call.

By using these tables, the compiler and program are able to ensure function calls resolve to the appropriate virtual function, even if you’re only using a pointer or reference to a base class!

Calling a virtual function is slower than calling a non-virtual function for a couple of reasons: First, we have to use the *__vptr to get to the appropriate virtual table. Second, we have to index the virtual table to find the correct function to call. Only then can we call the function. As a result, we have to do 3 operations to find the function to call, as opposed to 2 operations for a normal indirect function call, or one operation for a direct function call. However, with modern computers, this added time is usually fairly insignificant.

Also as a reminder, any class that uses virtual functions has a __vptr, and thus each object of that class will be bigger by one pointer. Virtual functions are powerful, but they do have a performance cost.

 12.6 -- Pure virtual functions, abstract base classes, and interface classes
 Index
 12.4 -- Early binding and late binding

Share this:

http://www.learncpp.com/cpp-tutorial/125-the-virtual-table/

virtual table(有180个评论)的更多相关文章

  1. C++: Virtual Table and Shared Memory

    See at: 补充栏3: C++对象和共享内存 (叙述内容和Link1的内容基本一致) <C++网络编程 卷1:运用ACE和模式消除复杂性> <C++ Network Progra ...

  2. virtual table for class

    虚函数表 说起虚函数,相信你我都可以自然而然的想到“多态”,因为多态的实现就依赖于虚函数的继承和重写(覆盖).那么,class又或者是object是如何来管理虚函数的呢?你我又会想到虚函数表. 虚函数 ...

  3. (C/C++学习)4.C++类中的虚函数表Virtual Table

    说明:C++的多态是通过一张虚函数表(Virtual Table)来实现的,简称为V-Table.在这个表中,主要为一个类的虚函数的地址表,这张表解决了继承.覆写的问题,保证其真实反应实际的虚函数调用 ...

  4. Virtual Table

    C++对象模型——吴泰 C/C++杂记 C++中的虚函数(表)实现机制以及用C语言对其进行的模拟实现 C++ 多继承和虚继承的内存布局 [已翻译100%] (虚继承参考,推荐) 图说C++对象模型:对 ...

  5. [转] When exactly does the virtual table pointer (in C++) gets set for an object?

    PS: http://stackoverflow.com/questions/7934540/when-exactly-does-the-virtual-table-pointer-in-c-gets ...

  6. C++对象的virtual table在内存中的布局

    (1)单一继承 (2)多重继承 (3)虚拟继承 参考:<深度探索C++对象模型>

  7. C++: virtual inheritance and Cross Delegation

    Link1: Give an example Note: I think the Storable::Write method should also be pure virtual. http:// ...

  8. [CareerCup] 13.3 Virtual Functions 虚函数

    13.3 How do virtual functions work in C++? 这道题问我们虚函数在C++中的工作原理.虚函数的工作机制主要依赖于虚表格vtable,即Virtual Table ...

  9. Standard C++ Programming: Virtual Functions and Inlining

    原文链接:http://www.drdobbs.com/cpp/standard-c-programming-virtual-functions/184403747 By Josée Lajoie a ...

随机推荐

  1. java三大版本解析

    JAVA三大版本代表着JAVA技术的三个应用领域:JAVASE.JAVAME.JAVAEE. JAVA以前很长一段时间被称为JAVA2,所以现在很多人习惯称为J2SE.J2ME.J2EE,它们表示的含 ...

  2. Dalvik虚拟机和JVM的对比

    Dalvik虚拟机与Java虚拟机有着很多相似的特性,都支持GC,JIT,JNI等等.其主要区别在于文件格式以及指令集不同,下面对两者的特性进行比较与讨论. Difference1:文件格式 Dalv ...

  3. 自定义安装MS Office Project2007会出错

    作者:朱金灿 来源:http://blog.csdn.net/clever101 今天使用虚拟光驱文件自定义安装MSOffice Project2007,如下图: 然后总是出现一个错误: 从网上找来一 ...

  4. CUDA与OpenCL架构

    CUDA与OpenCL架构 目录 CUDA与OpenCL架构 目录 1 GPU的体系结构 1.1 GPU简介 1.2 GPU与CPU的差异 2 CUDA架构 2.1 硬件架构 2.1.1 GPU困境 ...

  5. Struts2学习笔记 - Part.01

    1.关于Struts2中的struts.xml文件中action设置 <!-- 它是一个通用action,此处的*表明它可以处理任意的请求--> <action name=" ...

  6. 图片无损放大软件PhotoZoom分屏预览功能 ,简直好用!

    PhotoZoom是一款智能放大图片软件,很多用户在初次使用PhotoZoom,发现图片所处的区域上方有四个不同方式的预览选项.因为很多初学者使用时不明白这四个按钮有什么作用,所以小编接下来讲解一下P ...

  7. C#——面对对象之封装、继承、多态的简单理解

    一.封装 隐藏对象的属性和实现细节,仅对外公开接口,控制在程序中属性的读取和修改的访问级别. 简单来多,就是讲我们所需要的代码打包封装进入一个类里面,便于我们调用,操作.这就是封装. 这样就隔离了具体 ...

  8. 【转】DBSCAN密度聚类算法

    DBSCAN(Density-Based Spatial Clustering of Applications with Noise,具有噪声的基于密度的聚类方法)是一种很典型的密度聚类算法,和K-M ...

  9. 训练1-Z

    有一头母牛,它每年年初生一头小母牛.每头小母牛从第四个年头开始,每年年初也生一头小母牛.请编程实现在第n年的时候,共有多少头母牛? Input 输入数据由多个测试实例组成,每个测试实例占一行,包括一个 ...

  10. nyoj28-大数阶乘

    大数阶乘 时间限制:3000 ms  |  内存限制:65535 KB 难度:3 描述 我们都知道如何计算一个数的阶乘,可是,如果这个数很大呢,我们该如何去计算它并输出它? 输入 输入一个整数m(0& ...