Three conditions for polymorphic realization:

1) Have inheritance

2) Have virtual function rewrite

3) Have a superclass pointer (a superclass reference) to a subclass object

When the compiler finds a virtual function in a class, it immediately generates the virtual table Vtable for that class. The entries in the virtual function table are Pointers to virtual functions in the class. The compiler also implicitly inserts a pointer in this class, VPTR (which, for the VC compiler, is inserted at the first location of the class’s memory address), to the virtual function table. When the constructor of this class is called, in the constructor of the class, the compiler implicitly executes the code associated with VPTR and Vtable, that is, VPTR points to the corresponding Vtable, associating the class with the vtable of this class.

In addition, when the constructor of the class is called, the pointer pointing to the base class has become the this pointer pointing to the concrete class, so that the correct Vtable can be obtained by relying on this pointer, so as to truly connect with the function body. This is the basic principle of dynamic linking and realization of polymorphism.

#include "stdafx.h" #include <iostream> #include <stdlib.h> using namespace std; class Father { public: void Face() { cout << "Father's face" << endl; } virtual void Say() { cout << "Father say hello" << endl; }}; class Son:public Father { public: void Say() { cout << "Son say hello" << endl; }}; void main() { Son son; Father *pFather=&son; PFather ->Say(); }Copy the code

For the Father * pFather = & son; The pFather pointer to the base class has become the this pointer to the son class, so calling the pFather pointer is equivalent to calling the this pointer to the right of the equals sign, which is the function of the son class itself. Namely pFather – > Say (); This line of code calls the subclass’s Say () function. Therefore, we have successfully implemented a call to the subclass function with the parent pointer pFather, which is polymorphic.