简体   繁体   English

C ++中Vptr和Vtable的机制

[英]Mechanism of Vptr and Vtable in C++

In C++, during dynamic binding, consider the following example... 在C ++中,在动态绑定期间,请考虑以下示例...

class Base
{
  virtual void fun()
  {
     cout<<"Base";
  }      
};

class Derived : Base
{
   void fun()
   {
     cout<<"Derived";
   }
};

int main()
{
  Base *bptr;
  Derived d;
  bptr=&d;
  bptr->fun();
}

The output of the above function is "Derived" due to the declaration of virtual keyword/dynamic binding. 由于虚拟关键字/动态绑定的声明,上述函数的输出是“Derived”。

As per my understanding, a virtual table (Vtable) would be created which contains the address of the virtual functions. 根据我的理解,将创建一个包含虚函数地址的虚拟表(Vtable)。 In this case the virtual table created for the derived class points to the inherited virtual fun() . 在这种情况下,为派生类创建的虚拟表指向继承的虚拟fun() And bptr->fun() will be getting resolved to bptr->vptr->fun(); 并且bptr->fun()将被解析为bptr->vptr->fun(); . This points to the inherited base class function itself. 这指向继承的基类函数本身。 I am not completely clear on how the derived class function is called? 我不完全清楚如何调用派生类函数?

Just went through this link virtual table and _vptr 刚刚浏览了这个链接虚拟表和_vptr

It says that the workflow will be like .. 它说工作流程会像..

  1. base_ptr->base_vptr----> to check the access of virtual function in base class. base_ptr-> base_vptr ---->检查基类中虚函数的访问。

  2. base_ptr->derived_vptr->virtual_function()---> to call/invoke the virtual function. base_ptr-> derived_vptr-> virtual_function()--->调用/调用虚函数。

Hence the derived class virtual function is called.. Hope you find it helpful. 因此调用派生类虚函数..希望你发现它有用。

And bptr->fun() will be getting resolved to bptr->vptr->fun();. 并且bptr-> fun()将被解析为bptr-> vptr-> fun();. This points to the base class function itself. 这指向基类函数本身。

Wrong. 错误。 The Derived instance's vptr (a hidden field in each instance) points to the Derived vtable. Derived实例的vptr(每个实例中的隐藏字段)指向Derived vtable。

The Standard doesn't specify the mechanism by which polymorphism is implemented. 标准没有规定实现多态的机制。 All the Standard says is how it should work -- not how compiler vendors should implement it. 所有标准都说它应该如何工作 - 而不是编译器供应商应该如何实现它。

That being said, you have it pretty much right as far as GCC under Linux and MSVC under Windows is concerned, and I would expect most other compilers to be similar. 话虽如此,就Linux下的GCC和Windows下的MSVC而言,你已经非常正确了,我希望大多数其他编译器都是相似的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM