The "position" of variables

J

Julek

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?

Specifically, I want to know the answer for Visual C++ 2003, and
SunStudio.

Thanks in advance,
Julek
 
E

Erik Wikström

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.

But surely you can assume that all instances of a class/struct in a
running program have the same layout. Of course of you recompile the
program they layout can change but in each instance of a program it
should be well-defined.
 
E

Erik Wikström

No, you can't. Virtual bases aren't always at the same offset relative
to any particular derived class.

struct base
{
int i;
};

struct i1 : virtual base
{
int j;
};

struct i2 : virtual base
{
int k;
};

struct der : i1, i2
{
int m;
};

Let's say that, for an object of type i1, the compiler puts the base
subobject immediately after the direct members of i1, and for an object
of type i2, it puts the base subobject immediately after the direct
members of i2. Now where does that base subobject end up when you have
an object of type der? If it's immediately after the direct members of
i1, then it can't be immediately after the direct members of i2, so the
offset of i from the i2 subobject is different from the offset in a
standalone i2 object. And vice versa. So one of the offsets has to
change.

Yes, of course you can never make any assumptions about the offset of
member in one class based on the offset in another class. But the offset
of a member in different instances of the same class (which is what the
OP asked about) should be well defined.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,068
Latest member
MakersCBDIngredients

Latest Threads

Top