How to Access Virtual Table directly

1. Keep in mind that the memory that store an object always starts with its virtual function

 1 #include <iostream>
 2 
 3 class Base1 
 4 {
 5     public:
 6     virtual foo()
 7     {
 8         std::cout << "this is base1::foo()" << std::endl;
 9     }
10 };
11 
12 class Base2 
13 {
14     public:
15     virtual foo()
16     {
17         std::cout << "this is base2::foo()" << std::endl;
18     }
19 };
20 
21 class Child: public Base1, Base2
22 {
23     public:
24     // virtual foo()
25     // {
26     //      std::cout << "this is child::foo()" << std::endl;
27     // }
28 
29     virtual goo()
30     {
31         std::cout << "this is child::goo()" << std::endl;
32     }
33 };
34 
35 int main()
36 {
37     typedef void(*Fun)(void);
38 
39     Child child;
40     Fun pfun = nullptr;
41     pfun = (Fun)*((int*)*(int*)(&child));
42     pfun();
43     pfun = (Fun)*((int*)*(int*)(&child) + 2);
44     pfun();
45     pfun = (Fun)*((int*)*((int*)(&child) + 2));
46     pfun();
47 
48     // Base1 *test = new Child();
49     // test->foo();
50 
51     return 0;
52 }

猜你喜欢

转载自www.cnblogs.com/anarkitek/p/9108790.html
今日推荐