Unfortunately, most pointers that we pass to function write
as the first argument are not of type const char *
. To output objects of other types, we must convert the pointers to those objects to type const char *
; otherwise, the compiler will not compile calls to function write
. C++ provides the reinterpret_cast operator for cases like this in which a pointer of one type must be cast to an unrelated pointer type. Without a reinterpret_cast
, the write
statement that outputs the integer number
will not compile because the compiler does not allow a pointer of type int *
(the type returned by the expression &number
) to be passed to a function that expects an argument of type const char *
—as far as the compiler is concerned, these types are inconsistent.
A reinterpret_cast
is performed at compile time and does not change the value of the object to which its operand points. Instead, it requests that the compiler reinterpret the operand as the target type (specified in the angle brackets following the keyword reinterpret_cast
). In Fig. 14.11, we use reinterpret_cast
to convert a ClientData
pointer to a const char *
, which reinterprets a ClientData
object as bytes to be output to a file. Random-access file-processing programs rarely write a single field to a file. Typically, they write one object of a class at a time, as we show in the following examples.
Error-Prevention Tip 14.4
It’s easy to use reinterpret_cast to perform dangerous manipulations that could lead to serious execution-time errors.
Portability Tip 14.1
reinterpret_cast is compiler dependent and can cause programs to behave differently on different platforms. Use this operator only if it’s absolutely necessary.
Portability Tip 14.2
A program that reads unformatted data (written by write) must be compiled and executed on a system compatible with the program that wrote the data, because different systems may represent internal data differently.
18.117.91.2