Virtual function table is a table of virtual functions in C + + class, it is important to understand the virtual function table to understand polymorphism.
The compiler used this time is VS2013, in order to simplify the operation without having to manipulate the function pointer, I use the CL compile option of VS to see the memory layout of the class.
How to use CL:
(1) Open the "Visual Studio Tools" directory under the VS directory in the Start menu and find the "VS2013 developer command Prompt" to open it;
(2) Place the files you want to compile into the corresponding folder in the command line.
(3) Enter CL "filename"/d1reportsingleclasslayout "class name"
(Refer to the following blog for specific usage: http://www.cnblogs.com/dsky/archive/2012/02/07/2340984.html)
Example:
#include <iostream>usingnamespace std; class C {public: int A; int b;}; int Main () { return0;}
Output Result:
(1) Virtual function table for a single class
class C {public: virtualvoid foo () {} int m;};
Result Analysis: You can see that the virtual table is at the very beginning of the class, which is to improve efficiency and find virtual functions correctly.
(2) Single inheritance
class Base {public: virtualvoid v1 () {} int b;}; class Public Base {public: virtualvoid v2 () {} int D;};
Result analysis: At the front of the class derived is the class base, as we expected. Virtual tables are not both base and derived, but only base, and virtual functions in derived are placed in virtual tables in base.
(3) Single inheritance + overwrite
class Base { public : virtual void V1 () {} int b;}; class Derived: public Base { public : virtual void V1 () {} virtual void V2 () {} int D;};
Results Analysis: We covered the base in the derived v1, from the results can be seen in the virtual table of the original base::v1 into the DERIVED::V1
(4) Multiple inheritance
classBase1 { Public: Virtual voidv1 () {}intB1;};classBase2 { Public: Virtual voidv2 () {}intB2;};classDerived: PublicBASE1, PublicBase2 { Public: Virtual voidv3 () {}intD;};
Results analysis: Two base classes each have their own virtual table, and derived's virtual function is placed in the first virtual table.
(5) Virtual inheritance
classVbase { Public: Virtual voidvb1 () {}intvb;};classBASE1:Virtual PublicVbase { Public: Virtual voidv1 () {}intB1;};classBASE2:Virtual PublicVbase { Public: Virtual voidv2 () {}intB2;};classDerived: PublicBASE1, PublicBase2 { Public: Virtual voidv3 () {}intD;};
Result Analysis: After virtual inheritance, there is a virtual class table (vbtable) in the base class, and the virtual class table records the offset to the virtual class, such as 4+24 = 28. and the virtual function table is as we discussed earlier. Looking again, we find that the virtual base class is not part of the inheriting class, but rather is found by the Virtual class table.
Deep understanding of C + + virtual function table