Did you look up the documentation for write?
basic_ostream& write( const char_type* s, std::streamsize count );
The first parameter is const char_type* s
, which means for a std::ostream
you need to pass a type const char*
or char*
. write
does not accept any other types.
Now, personally I would write (char*)&(x)
as reinterpret_cast<char*>(&x)
, but leaving that aside, first you take the address of the object using the &
(the address-of operator). Next you cast it to a char*
. Since a char
is one byte, it writes one byte of the object at a time the number of characters specified in count
. The cast is there so that the object can be passed to write
and so it can spit out the binary representation of the object since you are writing one byte at a time. The char*
would point to the first byte of the object and write
knows how many bytes big the object is based on you passing sizeof(double)
as the second argument.
Note that this is a simple form of serialization.
On my computer the size of char is 1 byte, but that isn't always going to be true.
That is incorrect. char
is guaranteed to always be one byte.