C99 and C ++ are slightly different from this.
The C99 standard ensures that structure fields will be laid out in memory in the order in which they are declared, and that the fields of two identical structures will have the same offsets. See this question for the relevant sections of the C99 standard. To summarize: the offset of the first field is indicated to be zero, but the offsets after that are not defined by the standard. This allows C compilers to adjust the offsets of each field so that the field satisfies any memory alignment requirements in the architecture. Since this is implementation dependent, C provides a standard way to determine the offset of each field using the offsetof macro.
C ++ offers this guarantee only for Plain Old Data (POD) . C ++ classes that are not plain old data cannot be viewed like this. The standard gives the C ++ compiler quite a bit of freedom in how it organizes the class when the class uses multiple inheritance, has non-public fields or members, or contains virtual members.
What does this mean for your examples:
dataType1 firstMemberInsideStruct = (dataType1)(*instance2);
This line is fine only if dataType1, dataType2 and dataType3 are regular old data. If any of them is not present, then the customType structure may not have a trivial constructor (or destructor), and this assumption may not hold.
dataType1 firstMemberInTheObject = (dataType1) (*pointerToAnObject);
This line is not safe regardless of whether dataType1 , dataType2 and dataType3 , because the CustomType class has private instance variables. This makes it not a POD class, so you cannot assume that its first instance variable will be ordered in a certain way.
sfstewman Jul 05 '12 at 8:28 2012-07-05 08:28
source share