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


in c++, during dynamic binding, consider following example...

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 above function "derived" due declaration of virtual keyword/dynamic binding.

as per understanding, virtual table (vtable) created contains address of virtual functions. in case virtual table created derived class points inherited virtual fun(). , bptr->fun() getting resolved bptr->vptr->fun();. points inherited base class function itself. not clear on how derived class function called?

just went through link virtual table , _vptr

it says workflow ..

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

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

hence derived class virtual function called.. hope find helpful.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -