Type conversion transforms a value or object representation from one data type to another. Implicit conversions can hide assumptions and make comparisons or interfaces difficult to understand. section 6.4 section 9.7
Treat conversions as a maintenance concern:
- Avoid unions that overlay unrelated representations with hardcoded sizes; they depend on assumptions about layouts, bits, bytes, and architectures. section 6.4
- When binary conversion is required, let the compiler provide the size with sizeof and reverse the pointer conversion exactly. section 6.4
- Prefer explicit conversion functions over implicit conversion operators so mismatches produce errors and the conversion remains visible. section 9.7
- Prefer higher-level types and classes that aggregate data instead of exposing representation conversions, while handling API or language-module boundaries cautiously. section 6.4
A rational value conversion
An implicit operator double lets `if (r1 == 3)` silently convert a Rational during comparison. Replacing it with `r1.toDouble()` makes the operation explicit and exposes the imprecision of comparing a double. section 9.7
Listing 6.7 Using a union for type conversion
static const int bytes_per_int = 4; #1
union mixer {
char ch[bytes_per_int]; #2
int n;
};
int main() {
mixer converter;
converter.n = 42;
std::ofstream out("data.txt", std::ios::binary);
out.write(converter.ch, bytes_per_int);
return 0;
}
Inspect the union example to see how a fixed four-byte character array makes binary conversion rigid and nonportable. section 6.4
Listing 6.8 Using reinterpret_cast in a reasonable manner
int main() {
int n = 42;
std::ofstream out("data.txt", std::ios::binary);
out.write(reinterpret_cast<const char*>(&n),
sizeof(n)); #1
return 0;
}
Compare the safer binary example, which uses reinterpret_cast with sizeof(n) rather than a programmer-determined size. section 6.4




















