People who have been through C to C + + must want to know how the C + + compiler arranges members of a class. Here I make a brief introduction, and have some code for you to test, I hope to have a role for everyone.
In fact, the title here may be a bit large, simply put, the class of the non-static members are in the order of declaration in the memory area, and the static members of the class and the general static variable storage format. I don't start with simple things, Start with a relatively complex example of multiple inheritance. Look at the following code:
class Point2d
{
public:
int _x,_y;
virtual f(){}//保证Point2d有个虚拟指针
};
class Point3d:public Point2d
{
public:
int _z;
};
class Vertex
{
public:
virtual void h(){}//保证Vertex3d的第二基础类有个vptr
int next;
};
class Vertex3d:public Point3d,public Vertex
{
public:
int mumble;
};
Point2d,point3d,vertex,vertex3d's inheritance relationship can be seen. Look at the main function again
int main()
{
Vertex3d v3d;
Vertex*pv;
pv=&v3d;
int*x=&v3d._x;//获取v3d的成员的地址
int*y=&v3d._y;
int*z=&v3d._z;
int*n=&v3d.next;
int*mem=&v3d.mumble;
cout<<"*v3d= "<<&v3d<<endl;//输出第一个vptr
cout<<"*x= "<<x<<endl;//输出成员的x的地址
cout<<"*y= "<<y<<endl;//….
cout<<"*z= "<<z<<endl;//…..
cout<<"*pv= "<<pv<<endl;/.输出第二个vptr
cout<<"*n= "<<n<<endl;//…….
cout<<"*mem= "<<mem<<endl;//……..
return 0;
}
The result of my compile run in vc6.0 is:
&v3d = 0x0012ff64
x = 0x0012ff68
y = 0x0012ff6c
z = 0x0012ff70
pv = 0x0012ff74
n = 0x0012ff78
mem = 0x0012ff7c