Placement of C + + objects

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.