Now I am not getting how run time resolved below line using this Virtual table and virtual pointer. |
It's implementation dependent, but one way to do it is with an extra hidden member of class Base. This hidden member points to a table of function pointers (one for each virtual function in class Base). Any time a Base object (or a derived object) calls Fun, the compiler generates code to
- dereference the hidden member to point to the table.
- Get the appropriate function pointer in the table
- Call the function.
Now when you declare a derived class, the compiler generates a new table of virtual functions for class Derived. If Derived overrides one of Base's virtual functions, then the corresponding entry in the table points to the new function. If Derived defines new virtual functions, then they go at the end of the table.
Base* ptr = new Derived();
This creates a Derived instance, which means that it's vtab points to the function table for class Derived. The entry in the table for Fun() points to Derived::Fun().
ptr->Fun();
Even though ptr is of type Base, the vtab pointer in *ptr points to the function table for class Derived. So when you lookup the function, you find Derived::Fun(), not Base::Fun()
BTW, as you can see, this means that calling a virtual function is slightly more complicated than calling a function directly. Calling the virtual function means doing 2 memory references. Sometimes the compiler can figure out which one is being called and optimize the code, but in general it's more expensive.