For multiple instances of the same object, are member variables stored at the same offset?

Solution 1:

For multiple instances of the same object, are member variables stored at the same offset?

Yes.

If I create multiple instances of this object Foo1 and Foo2, will they always have the same padding?

Yes.

Is there ever a case where Foo1::b is stored at offset 0x04 and Foo2::b is stored at offset 0x08 for example?

No.


This assumption holds only within the program. Compile the program on another system, and the offset can be different there.

Solution 2:

Consider offsetof:

#define offsetof(type, member) /*implementation-defined*/
           

The macro offsetof expands to an integral constant expression of type std::size_t, the value of which is the offset, in bytes, from the beginning of an object of specified type to its specified subobject, including padding if any.

offsetof relies on compiler internals, though the offset of a member of some type is a constant expression.