Tuesday 26 January 2016

vptr and vtable - runtime polymorphism

C++ compiler creates a hidden class member called virtual-pointer or in  short vptr when there are one or more virtual functions. This vptr is a  pointer that points to a table of function pointers. This table is also  created by compiler and called virtual function table or vtable. Each  row of the vtable is a function pointer pointing to a corresponding  virtual function.
To accomplish late binding, the compiler creates this vtable table for  each class that contains virtual functions and for the class derived  from it. The compiler places the addresses of the virtual functions for  that particular class in ‘vtable’.
When virtual function call is made through a base-class pointer, the  compiler quietly inserts code to fetch the VPTR and look up the function  address in the VTABLE, thus calling the right function and causing  late/dynamic binding to take place.


class base
 {   virtual void funct1(void);
 virtual void funct2(void);
}; base b;

b.vptr = address of b.vtable
b.vtable[0]= &base::funct1()
b.vtable[1]= &base::funct2()

No comments:

Post a Comment