The blog has been migrated to: http://kulv.sinaapp.com /.
Test the virtual function table pointer inherited by multiple virtual functions in C ++
I have read a lot about the implementation mechanism of virtual functions. Let's verify it now ···
# Include <iostream> <br/> using namespace STD; </P> <p> Class A {<br/> virtual A () {}; <br/> }; </P> <p> Class B {<br/> virtual B () {}; <br/>}; </P> <p> class CC: Public, public B {<br/> int A; // 2*4 + 8 <br/>}; </P> <p> int main () <br/>{< br/> CC cc; <br/> cout <sizeof (CC) <Endl; <br/> // result 12 indicates that the subclass maintains a virtual function table for each parent class containing virtual functions. <Br/> // The Calling mechanism is troublesome. For details, refer to the in-depth exploration of the C ++ object-oriented model. </P> <p> A * pA = & CC; <br/> B * pb = & CC; </P> <p> cout <"& CC =" <& CC <Endl; <br/> cout <"Pa =" <Pa <Endl; <br/> cout <"PB =" <Pb <Endl; <br/> // The running result indicates that the VC compiler places the virtual function table pointer at 0 in the class memory layout offset. Of course, the implementation of different compilers may be different. <Br/> return 0; <br/>}< br/>
Running result:
12
& CC = 0012ff74
Pa = 0012ff74
PB = 0012ff78
Press any key to continue
Yes
The following code intentionally modifies the content of the virtual function table !!! Then there was a miracle ···
Class kulv {<br/> Public: <br/> virtual A () {cout <"I/'am class kulv: ()! "<Endl ;}; <br/> virtual B () {cout <" I/'am class kulv: B ()! "<Endl ;};< br/>}; </P> <p> int main () <br/>{< br/> kulv; <br/> kulv * pkulv = & kulv; </P> <p> int * P = (int *) & kulv; <br/> * P = * P + 4; </P> <p> pkulv-> (); <br/> // actually called B ()!!!! This proves that the virtual function pointer is at zero offset of the class. <br/> // You must access the virtual function table for each virtual function call, therefore, we need at least two finger operations, with low efficiency. <Br/> // The above call code may be changed to: (kulv->__ vfptr [0]) (& kulv); <br/> return 0; <br/>}
The running result is:
I'm class kulv: B ()!
To learn, you must remember to practice before you can truly feel the existence of knowledge.