Analysis of the bottom layer of the virtual function table
Class composition structure
The structure of the virtual function table
Code display
#include <iostream>
using namespace std;
class Base
{
public:
virtual void ShowInf()
{
cout << "Base" << endl;
}
virtual void ShowName()
{
cout << "Name" << endl;
}
};
using Func = void(*)(void);
int main()
{
Base obj;
cout << &obj << endl; // 对象的地址
cout << (int*)&obj << endl; // 虚函数表的地址
cout << (int*)*(int*)&obj << endl; // 访问虚函数表的第一个元素,即第一个虚函数的地址
Func fptr = (Func)*(int*)*(int*)&obj; // 访问第一个成员函数
Func fptr1 = (Func)*((int*)*(int*)&obj + 1); // 访问第二个成员函数
fptr(); // 调用第一个成员函数
fptr1(); // 调用第二个成员函数
}
Why (int*)&obj and &obj dereference results are different, but the output pointer address is the same?
(int*)&obj casts a pointer to a pointer to a variable of type int. We know that a variable of type int occupies 4 bytes, so it happens that the pointer points to the virtual function table in the obj class object. After dereference, it points to the virtual function table. The header element.
After &obj is dereferenced, it points to sizeof(class type) bytes, which points to the entire class.