You wrote that you want to find the memory offset. Although what FredOverflow writes in its entirety, you must make an instance of your Test class if you want to know the addresses a , b and c . For instance:
Test t; float *ptr = &t.a; float *ptr1 = &t.b; float *ptr2 = &t.c;
On my machine, this gives the following three addresses:
0x7fff564f8918 0x7fff564f891c 0x7fff564f8920
And you will notice that they are 4 bytes (or sizeof(float) ) and the size of Test is 12 bytes (using sizeof(Test) ). In addition, the &t address is 0x7fff564f8918 the same &t.a address. How the memory layout of an instance of the Test class is formed.
You can also find the offset of members of type POD with offsetof() .
cout << offsetof(Test, a) << endl; cout << offsetof(Test, b) << endl; cout << offsetof(Test, c) << endl;
Productivity
0 4 8
Note that offsetof(Test, b) is essentially the same as
(unsigned long long) &(((Test*) 0)->b) - (unsigned long long) (Test*) 0
Answer the following question:
This code will not work due to the same errors that were mentioned earlier. However, if you want to calculate the address of your y member origin and set it to 0 , you can do this as follows:
class Point3d { public: float x, y, z; }; Point3d origin; origin.y = 10;
Sets the output:
Old value: 10 New value: 0
Again, remember that this is only possible because Point3d is a type of POD .