c++ virtual table

class Base {

public:
	Base(int a): a_(a) {}

	virtual void f() { cout << "Base::f" << endl; }

	virtual void g() { cout << "Base::g" << endl; }

	virtual void h() { cout << "Base::h" << endl; }
private:
	int a_;
};

int main() {
	// your code goes here
	typedef void(*Fun)(void);

	Base b(5);

	Fun pFun = NULL;
	
	cout << "a_:" << *((int*)&b + 2) << endl;

	cout << "虚函数表地址:" << (int*)(&b) << endl;

	int* vtable = (int*)*(int*)(&b);
	cout << "虚函数表 — 第一个函数地址:" << vtable << endl;

	// Invoke the first virtual function

	//pFun = (Fun)*((int*)*(int*)(&b));
	pFun = (Fun)*(vtable);
	pFun();
	pFun = (Fun)*((int*)*(int*)(&b) + 2);
	pFun();
	pFun = (Fun)*(vtable + 4);
	pFun();
        cout << "vtable end: " << (Fun)*(vtable + 6) << std::endl;

       // vtable and end of vtable
       int** pVtab = (int**)&b;
       pFun = (Fun)pVtab[0][0];
       pFun();  // base::f
       pFun = (Fun)pVtab[0][1];
       cout << pFun << endl;
       pFun = (Fun)pVtab[0][2];
       pFun();  // base::g
       pFun = (Fun)pVtab[0][3];
       cout << pFun << endl;
       pFun = (Fun)pVtab[0][4];
       pFun();  // base::h
       pFun = (Fun)pVtab[0][5];
       cout << pFun << endl;
       pFun = (Fun)pVtab[0][6];
       cout << pFun << endl;
       pFun = (Fun)pVtab[0][7];
       cout << pFun << endl;


	return 0;
}
输出结果:

a_:5
虚函数表地址:0x7ffe3f0a5970
虚函数表 ? 第一个函数地址:0x400e70
Base::f
Base::g
Base::h
vtable end: 1
Base::f
0
Base::g
0
Base::h
0
1
1

Leave a Reply

Your email address will not be published. Required fields are marked *