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 ..
base_ptr->base_vptr----> check access of virtual function in base class.
base_ptr->derived_vptr->virtual_function()---> call/invoke virtual function.
hence derived class virtual function called.. hope find helpful.
Comments
Post a Comment