+ 1

How virtual function is implemented in Polymorphism?

20th Jun 2016, 1:06 AM
Utpal Kumar
Utpal Kumar - avatar
3 Answers
+ 2
It's usually implemented using a virtual function table. This table is generated by the compiler and cannot be "seen" from C++. It therefore only exists in the binary code. A virtual function table can be thought of as an array. The compiler puts pointers to the concrete implementations of the virtual functions in the virtual function table. An example: A function pointer for the virtual function "func" is always put into index 0 of the virtual function table. For class A the function pointer at index 0 points to the implementation of "func" in class A. In As subclass B, the virtual table index 0 points to Bs implementation, if "func" has been overridden in B, or to the implementation of class A if there's no implementation in B... and so on for subclasses of B. So instead of directly putting the address of the function to call in the code, for invoking "func" first always the function pointer at index 0 in the virtual table is retrieved and then the function is invoked. If there are other virtual functions, index entries 1, 2 etc are created and used.
20th Jun 2016, 12:20 PM
Stefan
Stefan - avatar
+ 1
the compiler adds a hidden pointer to your most based class that uses virtual functions, second each class containing a virtual function or is derived from a class uses virtual functions, is given its own virtual table. Its a static array created a compile time and contains one entry for each virtual function that can be called. Each entry in this array is a function pointer that points to the most-derived function accessible by that class. here a lilltle illustration: ------ bclass --------------- | *vptr; - - - - - - - -| - - - - - -> bclass virtuel table- | virtual func1(); <-| - - - - - - -| - - func1() | |- -| -> virtual func2(); <-| - - - - - - -| - - func2() | | -------------------------------- -------------------------------- | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -| | --- d1 : public bclass -- | | *vptr; (inherited) - |- - - -> d1 virtua table- | | virtual func1(); <- - -| - - - - -| - - func1() | | ---------------------------------- | func2() - - - |- - -| ------------------------
6th Nov 2016, 4:45 PM
siuilban
siuilban - avatar
0
related code: class bclass { public: virtual func1() { } virtual func2() { } }; class d1: public bclass { public: virtual func1() { } };
6th Nov 2016, 4:50 PM
siuilban
siuilban - avatar