C++的虚函数表一直以来很神秘,感觉是很高深的东西。
看了 http://www.learncpp.com/cpp-tutorial/125-the-virtual-table/ 这篇文章,顿时明白了什么是虚函数表。
没有虚函数的C++类,是不会有虚函数表的。
有虚函数的C++类,才会有虚函数表
class Base { public: virtual void function1() {}; virtual void function2() {}; private: int a; };
Base b;
int nSize = sizeof(Base);
nSize的大小为8. 此对象由 a 和 vfptr构成,vfptr是一个指针变量,它占据了对象b的前4字节内存,
所以*(unsigned*)&b的值就是Base的虚函数表所在的地址了*(unsigned*)(*(unsigned*)&b))的值,即为funtion1的地址了。