This is a really bad idea:
char *p=(char *)&d1;
*p=1;
Your code should never make assumptions about the internal structure of the class. If your class had any virtual functions, for example, that code would cause a crash when you called them.
I can only conclude that your Distance
class looks like this:
class Distance {
short feet;
float inches;
public:
void setFeet(...
};
When you setFeet(256)
, it sets the high byte (MSB) to 1 (256 = 1 * 2^8) and the low byte (LSB) to 0. When you assign the value 1
to the char
at the address of the Distance
object, you're forcing the first byte of the short
representing feet to 1. On a little-endian machine, the low byte is at the lower address, so you end up with a short
with both bytes set to 1, which is 1 * 2^8 + 1 = 257
.
On a big-endian machine, you would still have the value 256, but it would be purely coincidental because you happen to be forcing a value of 1 on a byte that would already be 1.
However, because you're using undefined behavior, depending on the compiler and the compile options, you might end up with literally anything. A famous expression from comp.lang.c is that such undefined behavior could "cause demons to fly out of your nose".