Saturday 23 June 2012

Explain virtual table (v-table) mechanism (dynamic binding/late binding)

As soon as you declare some method in your class as virtual compiler creates a virtual table for that class and adds a pointer to it (vptr) to it. Virtual table is an array whose elements are pointers to virtual functions. Compiler assigns virtual table for each class that implements or declares virtual functions. Virtual method pointer points to the function implementation in the most derived class. Derived classes inherit vptr which is updated and points to virtual table of that particular class.

In the run-time, when we call virtual function through base class pointer which points to derived class object, virtual table of derived class is accessed (via vptr) and examined for function pointer.

No comments:

Post a Comment