How are objects stored in memory in C++?
For a regular class such as
class Object { public: int i1; int i2; char i3; int i4; private: };
Using a pointer of Object as an array can be used to access i1 as follows?
((Object*)&myObject)[0] === i1?
Other questions on SO seem to suggest that casting a struct to a pointer will point to the first member for POD-types. How is this different for classes with constructors if at all? Also in what way is it different for non-POD types?
Edit:
In memory therefore would the above class be laid out like the following?
[i1 - 4bytes][i2 - 4bytes][i3 - 1byte][padding - 3bytes][i4 - 4bytes]
Almost. You cast to an Object*, and neglected to take an address. Let’s re-ask as the following:
You have to be really careful with assumptions like this. As you’ve defined the structure, this should be true in any compiler you’re likely to come across. But all sorts of other properties of the object (which you may have omitted from your example) will, as others said, make it non-POD and could (possibly in a compiler-dependent way) make the above statement not true.
Note that I wouldn’t be so quick to tell you it would work if you had asked about i3 — in that case, even for plain POD, alignment or endianness could easily screw you up.
In any case, you should be avoiding this kind of thing, if possible. Even if it works fine now, if you (or anybody else who doesn’t understand that you’re doing this trick) ever changes the structure order or adds new fields, this trick will fail in all the places you’ve used it, which may be hard to find.
Answer to your edit: If that’s your entire class definition, and you’re using one of the mainstream compilers with default options, and running on an x86 processor, then yes, you’ve probably guessed the right memory layout. But choice of compiler, compiler options, and different CPU architecture could easily invalidate your assumptions.