Get C + + virtual table address and virtual function address
by Qianghaohao
Have learned C + + should have heard about the virtual table, there is not too much to introduce the concept, through the real
Example to demonstrates how to obtain a virtual table address and a virtual function address.
Briefly describe the concept of a virtual table: if there is a virtual function in a class, then the instance of this class has
A virtual table pointer points to a virtual table, which is a memory that is dedicated to storing the virtual function address of the class.
The diagram illustrates the topic of this article (it is easier to look at the pointer in the following code):
the code is as follows ( This is explained in the comments in the code):
Class Base {public:virtual void F () {cout << "base::f" << Endl;} virtual void g () {cout << "base::g" << Endl;} void H () {cout << "base::h" << Endl;}}; typedef void (*fun) (void); function pointer int main () {Base B; Here the pointer operation is more chaotic, in this slightly resolved://*****printf ("Virtual table Address:%p\n", * (int *) &b); Parsing * * * * *://1.&b represents the starting address of object B//2. (int *) &b strong to int * type, in order to take the first four bytes of the B object, the first four bytes is the virtual table pointer//3.* (int *) &b take the first four bytes, that is vptr the virtual table address////*****PRINTF ("the first virtual Function Address:%p\n ", * (int *) * (int *) &b) * * * * * * * * * * * * * * * * * (int *) &B is vptr, that is, virtual table pointer. and the virtual table is a virtual function pointer///So the virtual table each element (virtual function refers to Pin) is 4 bytes under the 32-bit compiler, so (int *) * (int *) &B//Such a strong turn to fetch four bytes later. so * (int *) * (int *) &B is the first element of a virtual table. That is, the address of f (). Then the second virtual function address is followed and so on. Always remember that vptr points to a piece of memory,//This memory holds the virtual function address, this memory is what we call the virtual table. printf ("Virtual table Address:%p\n", * (int *) &b); printf ("First virtual function Address:%p\n", * (int *) * (int *) &b); printf ("Second virtual function address:%p\n", * (int *) * (int *) (&B) + 1)); Fun Pfun = (fun) * ((int *) * (int *) (&b)); Vitural f (); printf ("f ():%p\n", pfun); Pfun (); Pfun = (Fun) (* (int *) * (int *) (&B) + 1)); Vitural g (); printf ("G ():%p\n", pfun); Pfun ();}
Reference Documents:
http://blog.csdn.net/haoel/article/details/1948051(Note: There is a problem with the address code of the virtual table in this article)
Get C + + virtual table address and virtual function address