Implicit conversion lets C++ change one type into another without an explicit request. A single-parameter constructor can turn a double into a Circle or Complex, while a conversion operator can turn a Rational into a double. section 2.2 section 9.7
The convenience can hide meaning, produce misleading comparisons or output, and add construction work. Mark conversion constructors explicit when silent conversion is not intended; replace conversion operators with named functions such as toDouble(). section 9.7 section 9.8
Use these checks when reviewing conversion-heavy code:
- Identify constructors that accept one argument and determine whether the compiler may use them during calls or expressions. section 2.2
- Replace an uncontrolled conversion constructor with explicit when callers should request construction directly. section 2.2
- Prefer named conversion functions when a value should become another type only at an obvious call site. section 9.7
- Provide overloads for mixed-type operations when they avoid unnecessary temporary objects and constructor conversions. section 9.8
Rational values that look like numbers
A Rational class with operator double() allows `std::cout << r1` and `if (r1 == 3)` to compile through conversion. The output and comparison use the approximate double value, although the source appears to use a rational object directly. Replacing the operator with `r1.toDouble()` makes both conversions visible. section 9.7
Listing 9.20 Implicit, silent, and expensive constructor type conversions
class Complex {
private:
double real;
double imag;
public:
Complex(double real, double imag=0) : real(real), imag(imag) {}
double getReal() const { return real; }
double getImag() const { return imag; }
};
const Complex operator+(const Complex& lhs, const Complex& rhs) {
return Complex(lhs.getReal()+rhs.getReal(), lhs.getImag()+rhs.getImag());
}
int main() {
Complex c1(2.2); #1
Complex c2 = c1 + 3.14159; #2
Complex c3 = 2.71828 + c1; #3
Complex c4 = 2.71828 + 3.14159; #4
}
Trace how Complex expressions silently construct temporary objects, then compare them with overloads that accept double directly. section 9.8



