First, function call bundle
1, definition
Bundle: Connect the function body to the function call called bundle. When the bundle is completed before the program is run (by the compiler and connector), it is called early bundle. (C Compilation is only one function call, that is, bundled up) If the bundle occurs when running, it is called evening bundle (or dynamically bundled, running time).
Virtual function: If we add keyword Virtual before defining the base class, you will tell the compiler to be tied to this function and automatically install the evening bundled implementation mechanism.
2, realize
The compiler creates a table (called vtable) for each class that contains virtual functions. In this table, put a specific class virtual function address, in addition, a VPTR pointer is held in this class, pointing to the VTABLE of this object. When the function is called by the base class pointer (the compiler statically plans the VPTR of the sub-object so that the correct function can be called to achieve the evening bundle.
#include
Class base {public: Virtual void f () {cout << "base-print" << endl;};
Class Derived: Public Base {public: Void f () {cout << "derived-print" << endl;}};
Void main () {base * b; // (1) Derived * d = new deerived; // (2) b = d; // (3) B.f (); // (4)}
RESULTS: Derived-Print
The figure is as follows: