Dynamic binding experience

zhaozj2021-02-08  213

I have never seen it in front of "Thinking In C " to have a bit experience for dynamic binding, saying to share with you.

If a base class (no parent class) contains virtual functions, then when compiling, the compiler generates a virtual function table, the table is the address of all virtual functions in this class (in order to arrange); and will be here Dynamic insertion into a member variable (__vfptr) in the class, which is a pointer to this virtual function table. For all subclasses of this base class, both compilers generate their virtual function tables and point to it. E.g

Class bb {

PUBLIC:

BB ();

Virtual ~ bb ();

Virtual void f1 () {cout << "bb" << endl;};

}; // bb virtual function table in a function of ~ bb (), the second is F1 ();

Class Dd: public bb {

PUBLIC:

DD ();

Virtual ~ dd (); // The first function in the table

Virtual void f1 () {cout << "DD" << endl;}; // second

}

A function in the virtual function table in the BB is ~ DD (), the second is the F1 () of DD; if the BB does not define F1 (), // Virtual F2 (); then the second function is BB F1 (), the third is F2 (); if there is a call:

DD DD;

BB * PBB = & DD;

PBB-> F1 (); // Output "DD"

Because the compiler pairs PBB-> F1 () is not the address directly Call F1, it is similar to:

MOV ECX, DWORD PTR [EBP-20H]; // PBB variable content = product address = __ vfptr address

MOV EDX, DWORD PTR [ECX]; // __ vfptr's content = VTABLE's first address

Call DWORD PTR [EDX 4] // Call the second function of the virtual function table: DD.F1 ()

For example Class CC {

PUBLIC:

CC ();

Virtual ~ cc ();

Virtual void f2 () {cout << "cc" << endl;};

}

Class Dd: Public BB, Public CC {...}

There is a call:

DD DD;

Void * pcc = (cc *) & dd; // The key is this sentence! ! !

BB * PBB = (bb *) PCC;

PBB-> f1 (); // Output is "CC", that is, calling CC :: F2 () !!!

This is because there are two __vfptr in DD (one BB, one is CC), respectively, in the first two digits of DD object data space, all points to DD's virtual functions. In fact, in the second PCC pointing to the second __vfptr (CC), according to the above assembly code, you can know the interpretation of the compiler to the PBB-> F1 () is called "The" virtual function table "second function (Because F1 () in the second of BB), and "that" virtual function is already CC.

转载请注明原文地址:https://www.9cbs.com/read-1902.html

New Post(0)