In this statement why cast x to char* and not to bool*-
out.write( (char*)&(x), sizeof(double) );
In this statement why cast x to char* and not to bool* ...
It suspect you are thinking that a bool
, conceptually a single bit, is the most basic data type in C++. That is not the case. Individual bits are not addressable in C++. The C++ memory model is organized around the concept of a byte, which must contain at least eight bits. By definition, a char
(and related types signed char
and unsigned char
) is exactly one byte long.
That bits aren't addressable means the concept of a boolean data type doesn't quite fit into the memory model. Consecutive booleans either have gaps between them (which would be problematic for your proposed cast to bool*
) or a boolean can contain far more values than just false
and true
(also problematic; a boolean that contains some value other than false
or true
is undefined behavior).
The C++ I/O model extends the byte-based memory model to I/O. A C++ I/O stream comprises a sequence of bytes (and sometimes multiple bytes in the case of wide chars) rather than a sequence of bits. This is why std::basic_ostream::write
takes a pointer of some character type (typically char
) and a size as the arguments.