C + + Class object memory structure
First, we introduce the layout of class object memory in C + + with inheritance relationship: in C + +, if there is a virtual function in a class, then it has a pointer __vfptr of the virtual function table in the first memory data of the class object. The memory data for the member variables in the class is followed by.
For subclasses, the first memory data records the copy of the parent class object (including the parent class virtual function table pointer and the member variable). The following is the subclass's own member variable data.
The same principle is true for subclasses of subclasses. However, no matter how many subclasses are inherited, there is always only one virtual function table pointer in the object.
To explore the memory layout of C + + class objects, write several classes and functions first
First write a base class:
class Base
{
public:
virtual void f() { cout << "Base::f" << endl; }
virtual void g() { cout << "Base::g" << endl; }
virtual void h() { cout << "Base::h" << endl; }
int base;
protected:
private:
};
Then, we study the memory object structure of subclasses in a variety of different inheritance situations.
1. No virtual function set inheritance
//子类1,无虚函数重载
class Child1 : public Base
{
public:
virtual void f1() { cout << "Child1::f1" << endl; }
virtual void g1() { cout << "Child1::g1" << endl; }
virtual void h1() { cout << "Child1::h1" << endl; }
int child1;
protected:
private:
};
This subclass Child1 does not inherit a virtual function of any of the base classes, so its virtual function table is as follows:
We can see that in the virtual function table of subclasses, the virtual function of the base class is stored first, and the virtual function of the subclass is stored.