vtable & _vptr

Virtual Table is a lookup table of function pointers used to dynamically bind the virtual functions to objects at runtime. It is not intended to be used directly by the program, and as such there is no standardized way to access it.

虚表是一张函数指针的查找表,这些函数指针用来在运行时动态的绑定虚函数到对象上。他的初衷就不是被程序直接运用的,所以没有标准的方法可以接触到它。

Virtual Table:

Every class that uses virtual functions (or is derived from a class that uses virtual functions) is given it's own virtual table as a secret data member.

每一个利用虚函数的(或者其父类有虚函数的)类都有一张自己的虚函数表,其是作为一个秘密的数据成员存在的
This table is set up by the compiler at compile time.

这张表是编译器在编译的时候生成的。
A virtual table contains one entry as a function pointer for each virtual function that can be called by objects of the class.

一张虚函数表包括一条条目,该条目是给每一个虚函数的函数指针,这些指针能够被类的对象所调用。
Virtual table stores NULL pointer to pure virtual functions in ABC.
虚函数表对ABC中纯虚函数存放NULL指针。

Virtual Table is created even for classes that have virtual base classes. In this case, the vtable has pointer to the shared instance of the base class along with the pointers to the classe's virtual functions if any.

虚函数表对有虚基类的类也是有的。在这种情况下,vtable不仅有基类的指针,还有类虚函数的指针。


_vptr :

This vtable pointer or _vptr, is a hidden pointer added by the Compiler to the base class. And this pointer is pointing to the virtual table of that particular class.

_vptr是一个隐藏的指针,其是通过编译器加到基类上去的。而这个指针就只想特定的类的虚函数表。
This _vptr is inherited to all the derived classes.
_vptr被继承到所有的派生类中
Each object of a class with virtual functions transparently stores this _vptr.
每一个类的对象都显式地存放有_vptr
Call to a virtual function by an object is resolved by following this hidden _vptr.

通过这个隐藏的_vptr,我们可以调用对象的虚函数。

对于这张图,我们要特别注意_vptr指针的情况,因为这个指针决定了继承类多态特性的可能。

D1 class's destructor and then calls the destrcutor of Base class - this as part of when dervied object gets deleted it turn deletes it's emebeded base object. Thats why we must always make Base class's destrcutor as virtual if it has any virtual functions in it.

先是调用派生类的析构函数,然后再调用基类的析构函数,这就是为什么当基类中有虚函数时我们一定要将其析构函数定义成虚函数的原因。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值