Can we assume member variables reside in a class as they would in a structure? It is legitimate to assume the memory layout of the field of a structure. Can we assume the same for a class?
You may. C only has structs. C++ is a replacement for C. Therefore, C++ onlky has structs. The C++ class is an appeasment to the object technology folks who speak of classes and unless C++ has one, the impression would be that C++ can't do objects. However, the underlying implentation of a C++ class is a struct.
Rephrasing, if you declare each of your struct members as public/private/protected, there is no difference between a class and a struct.
The one difference between the two is the
default access specifier. For a struct the default is public: for a class the default is private.
char* p = (char*)&s.x;
What!!! First, this is a bad cast. Second, it's a C cast and not a C++ cast. s.x is a long and no amount of fiddling will make a char.
Worse, there is a presumption that the low 8 bits of a the long is a signed char-including the sign bit.
In memory both s.x and s.y are 4-bytes and assuming compiler packs memory then
You said it yourself:
assuming compiler packs... Generally, variables are laid out on int boundaries. That means there can be slack bytes. The compiler will adjust the pointer arithmetic to take this into account ---->>>>>Right up until you pull a cast and make assuptions about memory.
Therefore:
Does q point to first byte of t.y? Always?
is a definite could be.
Please do not make assumptions in C++ and especially do not cast. A cast in C++ means one of two things a) you are calling a relic C function and you have to cast to a void* or somesuch thing, or b) your C++ design is screwed up.