c++ memory in array of class objects
c++, class, layout, member, memory
Solution
`sizeof Object` already includes all internal padding of the class `Object`. including any padding at its end. Arrays don't allow any additional padding. Therefore it is true that `data_ptr + sizeof Object` will have the address of `array[1].data`.
However I'm not sure if this is actually allowed. That is, the compiler might be allowed to assume that you never add a value larger than 8 (the size of the member array `data`) to `array[0].data`, and therefore it might apply optimizations that fail if you violate the rules. That is, your code might actually exhibit undefined behavior (which is the standard term for "the compiler is allowed to do anything in this case").
However since you are using a pointer to `char`, for which there are more permissive rules (you can do many things with `char*` which you could not do with general types), it may be that it's actually defined behaviour anyway.
Problem
I have a class like this: ``` class Object { public: unsigned char data[8]; // other variables // functions etc... }; ``` The question is - are the object members all stored in the same place in memory relative to the object? So if I have an array: Object array[3], given a char pointer `char* data_ptr = array[0].data`, will `data_ptr + (sizeof(Object))` then always point to array[1].data? (I've read a couple of Q/As about how there might be padding inbetween data members of classes and structs - but I don't think they answer my question.) Thanks in advance, Ben