The following program output is always 1 1 1. In “Inside the c++ object model” book, it is mentioned that it will give offset. The purpose is also to find out object layout. But, I am confused with the output. Used g++ 4.5.2
class Test
{
public:
float a;
float b;
float c;
};
int main()
{
float Test::*ptr = &Test::a;
float Test::*ptr1 = &Test::b;
float Test::*ptr2 = &Test::c;
cout<<ptr<<endl;
cout<<ptr1<<endl;
cout<<ptr2<<endl;
return 0;
}
Output:
1
1
1
Edit(Follow up question):
In the book it is mentioned that origin.y = 0 can be transformed to &origin + (Point3d::y-1) where origin is an object to Point3d and y is member variable of class Point3d. Though When I compiled it gave me compilation error.
You wrote that you wanted to find the memory offset. While what FredOverflow writes is completely true, you should make an instance of your class
Testif you want to know the address ofa,bandc. For instance:On my machine this yields the following three addresses:
And you will notice that they are 4 bytes (or
sizeof(float)) apart and that the size of aTestis 12 bytes (usingsizeof(Test)). Furthermore, the address of&tis0x7fff564f8918the same address of&t.a. That’s how the memory layout of an instance of the classTestis formed.You can also find the offset of members of a
PODtype by usingoffsetof().Yields
Note that
offsetof(Test, b)is essentially the same asAnswer to your followup question:
That code will not work because of the same errors as previously mentioned. However, if you wanted to calculate the address of your
ymember oforiginand assign it the value0it can be done thusly:Yields the output:
Again remember that this is only possible because
Point3dis aPODtype.