Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

virtual functions - Mechanism of Vptr and Vtable in C++

In C++, during dynamic binding, consider the following example...

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

class Derived : public 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.

As per my understanding, a virtual table (Vtable) would be created which contains the address of the virtual functions. In this case the virtual table created for the derived class points to the inherited virtual fun(). And bptr->fun() will be getting resolved to 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just went through this link virtual table and _vptr

It says that the workflow will be like ..

  1. base_ptr->base_vptr----> to check the access of virtual function in base class.

  2. base_ptr->derived_vptr->virtual_function()---> to call/invoke the virtual function.

Hence the derived class virtual function is called.. Hope you find it helpful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...