Get the address offset of a C + + class member variable

Source: Internet
Author: User

Today there are students in school asking how to get the address offset of member variables in a class, this should be a curious question for many beginners of C + +. I used to have this kind of demand when I was in school. Forget to write "strange program", anyway, you need to get the address offset of the member variable of a class.

In fact, the problem is very simple, if you understand the C + + class object Memory distribution, this is not a problem at all. I gave him an example:

struct A

{

int i;

};

& (*) 0)->i; This allows you to get to the offset. He said he didn't understand, OK, let's have a concrete talk.

If you define a variable A; We all know that &a indicates that the first address of variable a,& (A.I) represents the address of the variable i, then the & (A.I) minus &a does not get the offset of I?

Yes, it's that simple. So what does this example & (A *) 0 have to do with->i;?

The Address for & (A *) 0) is 0, so & ((A *) 0)->i equals & ((A *) 0)->i minus 0.

The student was even more curious, why & (A *) 0)->i no problem? This example does not allocate memory for the object of a, so how can I get its address?

Yes, there is no memory allocated here, but in this case we do not require memory and we do not operate on the memory, so it will not lead to a crash.

& ((a) 0)->i just uses the compiler to figure out its address for us. When the compiler wants to use a member variable, it gets the address of the member variable based on the object's first address plus the member's offset. When the object's first address is 0 o'clock, the resulting member variable address is its offset.

Come here, understand!

Get the address offset of a C + + class member variable

Related Article

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.