Friday, June 15, 2007

3.6 Pointer to Data Members

Useful feature of the language, if you need to probe at the underlying member layout of a class. One example of such a probing might be to determine if the vptr is placed at the beginning or end of the class. A second use might be to determine the ordering of access sections within the class.

& class_name::data_member is going to yield the offset within the class object. each actual member offset is bumped up by 1. to distinguish between a pointer to no data member and a pointer to the first data member.

float Point3d::*p1 = 0;
float Point3d::*p2 = &Point3d::x;
//oops: how to distinguish?
if ( p1 == p2) {...}

& object_name.data_member yields the membejr's actual address in memory. The result adds the offset of data member (minus 1) to the beginning address of the object. The value returned is of type float * because it refers to an specific single instance, much the same as taking the address of a static data member.

No comments: