Focus on the basics first otherwise this will confuse you.
Basically structure/class members are stored as a data structure in memory, one after the other. So if you have:
Code:
class foo
{
int x;
char y[10];
double z;
};
then at an instantiation of class foo at address 1000 then **depending on how the compiler implements this**, there could be an integer at 1000, 10 chars at 1004 and a double at 1014. So to get at z without an accessor function, assuming the definition foo bar;, you would use something like char *hack=(char*)&bar; double *z_ptr=&(hack[14]);
Tried it in Visual Studio 2008:
Code:
struct emp
{
private:
int x;
char y[10];
double z;
public:
void wibble()
{
printf("this=0x%08lx; &x=0x%08lx; &y=0x%08lx; &z=0x%08lx\n",this,&x,&y,&z);
}
void setdata(double a)
{
z = a;
}
}emp1;
void hackemp()
{
emp1.setdata(5.7);
emp1.wibble();
char *hack=(char*)&emp1;
double *z_ptr=(double*)&hack[16];
printf("hack=0x%08lx; z_ptr=0x%08lx\n",hack,z_ptr);
printf("emp1.z=%f\n",*z_ptr);
}
wibble just prints the addresses of this, x,y and z.
The first printf just checks I've worked out z_ptr correctly.
The second printf displays the value of z without using an accessor function.
Output:
Code:
this=0x00417140; &x=0x00417140; &y=0x00417144; &z=0x00417150
hack=0x00417140; z_ptr=0x00417150
emp1.z=5.700000
***THIS IS NOT PORTABLE AND IS NOT RECOMMENDED***
Use *only* if you have no other choice.
An accessor function is much better.