Virtual functions are the key to implementing polymorphism in C ++. Without virtual functions, C ++ can only be ob and cannot complete oo. I have read many articles about the implementation mechanism of virtual functions in VC ++. The links are as follows:
Http://blog.csdn.net/haoel/article/details/1948051. I think it is still a bit unclear, so I did a further experiment and recorded it for reference.
This article describes the layout of classes with virtual functions in memory and the memory layout of their instances (objects) without inheritance.
1. Source Code
# Include <iostream> # include <stdio. h> using namespace STD; Class cvirtual {public: int X; public: Virtual void VF () {cout <this-> x <Endl; cout <"hello" <Endl;} public: cvirtual (int x) {This-> X = x ;}}; typedef void (cvirtual: * Fun) (); Union {Fun f; unsigned int ADDR;} ut; int main (INT argc, char ** argv) {// print out the cout instance size <"object size:" <sizeof (cvirtual) <Endl; cvirtual * P = new cvirtual (999 ); cvirtual * P1 = new cvirtual (888); // print the object address cout <"address of the new object:" <p <Endl; // print the first member variable address cout <"Address of the first member variable in the object:" <& P-> x <Endl; // print the URL of the virtual function ut. F = & (cvirtual: VF); cout <"Address of the first virtual function in the class:" <STD: Hex <STD: showbase <ut. ADDR <Endl; // virtual table pointer unsigned int vptr = * (unsigned int *) P); cout <"virtual table pointer in object 1 (virtual table address) is: "<STD: Hex <STD: showbase <vptr <Endl; // the first value of the virtual table is unsigned slot0 = * (unsigned int *) vptr); cout <"value of the first item in the virtual table (the first virtual function address):" <STD: Hex <STD :: showbase <slot0 <Endl; // virtual table pointer unsigned int vptr1 = * (unsigned int *) P1 ); cout <"virtual table pointer (virtual table address) in object 2 is:" <STD: Hex <STD: showbase <vptr1 <Endl; // The first value of the virtual table is unsigned slot01 = * (unsigned int *) vptr1); cout <"the value of the first item in the virtual table (the first virtual function address ): "<STD: Hex <STD: showbase <slot01 <Endl; // prototype typedef void (_ thiscall * myfun) of the virtual function) (void * pthis); // call the first function in the virtual function table myfun F = (myfun) slot0; f (p); // call the virtual function myfun F1 = (myfun) ut. ADDR; F1 (p); Delete P; Delete P1; CIN> argc ;}
2. Results
3. Memory Layout
4. Conclusion
- The virtual function table is inCompilation phaseIt has been determined that it is established in the Data zone. During the runtime, the constructor only sets the vptr value of the object to this address, and all instances of the same class share the same virtual function table;
- Every project in the virtual function tableNot necessarily the address of the virtual function.Is probably a proxy function, and then the proxy function calls the virtual function;