Item 24: Declare Non-Member Functions When Type Conversions Should Apply to All Parameters

If you need type conversion on all parameters (including this), that function must be non-member.

For example, to implement Rational that supports:

Rational x, y, z;
y = x * 2;
z = 4 * y;

You need:

  • Non-explicit constructor
Rational(int numerator = 0, int denominator = 1);
  • Type conversion on all parameters (including this)
const Rational operator*(const Rational& lhs, const Rational& rhs);
  • That is because only parameters are eligible for implicit type conversion

  • Note: Templates follow a different rule

Creative Commons License
This blog by Che-Liang Chiou is licensed under a Creative Commons Attribution 4.0 International License.