Download Full-text http://download.csdn.net/detail/Dreamcode/201005 from csdn download center
(1) virtual functions
Let's take a look at a simple piece of code:
Code segment:
Line01: # include <stdio. h>
Line02:
Line03: class base {
Line04: public:
Line05: Virtual void _ stdcall output (){
Line06: printf ("class base \ n ");
Line07 :}
Line08 :};
Line09:
Line10: Class derive: public base {
Line11: public:
Line12: void _ stdcall output (){
Line13: printf ("class derive \ n ");
Line14 :}
Line15 :};
Line16:
Line17: void test (base * P ){
Line18: p-> output ();
Line19 :}
Line20:
Line21: int _ cdecl main (intargc, char * argv []) {
Line22: derive OBJ;
Line23: Test (& OBJ );
Line24: Return 0;
Line25 :}
The "output" function of the base class is a virtual function. Obviously, the program running result will be:
(2) virtual function table
First, we will analyze the object OBJ of the derive class in our main function to see its memory layout. Since there is no data member, its size is 4 bytes and there is only one vfptr, so the OBJ address is the vfptr address.
For a C ++ class, if it is to present polymorphism (the General compiler will take this class and whether its base class contains the virtual keyword as the class to be polymorphism ), the class will have a virtual function table, and each instance (object) will have a virtual function pointer (vfptr) pointing to the starting address of the virtual function table of this class, the content of the memory unit corresponding to the virtual function table address is the virtual function address (in fact, it is not the real function address, but the address of the JMP Instruction of the function ).
(2) Implement Virtual Functions