Re: The "position" of variables
On 2008-05-29 08:21:32 -0400, Julek <julekmen@go2.pl> said:
Hi,
I wanted to know, if there is guarantee that a specific variable is
always the same number of bytes forward than the beginning of the
struct/class. Example:
class MyClass
{
...
int var;
};
...
// somewhere we create one object
MyClass obj;
...
// somewhere else we create other object
MyClass *obj2=new MyClass;
...
// check the distance from the beginning of structure
int diff1=int( ((char*)&obj.var) - ((char*)&obj) );
int diff2=int( ((char*)&obj2->var) - ((char*)obj2) );
if(diff1 == diff2 )
{
// it's the same distance
}
Can I always assume, that diff1 == diff2, no matter how MyClass
structures are created? Even if they have multiple inheritance and
other "advanced" features?
Yes. But note that this is a somewhat constrained question: var is a
direct member of MyClass. More generally, no, you can't assume that any
member of a class will always be at the same offset. In particular,
virtual base classes (and, hence, their members) can move around,
depending on how inheritance is used.
Formally, the calculation of diff1 and diff2 is equivalent to the macro
offsetof, which can only be applied to POD types. The more general way
of pointing at a selected member of an arbitrary object of type T is
with a pointer to member of T:
int MyClass::*ptr = &MyClass::var;
MyClass obj1;
obj1.*ptr = 3; // assigns to obj1.var
MyClass obj2;
obj2.*ptr = 4; // assigns to obj2.var
If you have a pointer instead of an object or a reference, use ->* to
get at the member:
MyClass *pmc = &obj1;
int i = pmc->*ptr; // copies from obj1.var
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)