class Rational {
const Rational operator*(const Rational& rhs) const
...
};
Rational oneHalf(1,2);
Rational result = oneHalf * 2; // fine (with non-explicit ctor)
result = 2 * oneHalf; // error! (even with non-explicit ctor)
It was mentioned by scott meyers in Effective C++ book as below
Even when Rationl's constructor is not explicit, one compiles and one doesnot. Reason is given as below:
It turns out that parameters are eligible for implicit conversion "only if they are listed in the parameter list".
The implicit parameter corresponding to object on which member function is invoked -- the one "this" points to -- is never eligible for implicit conversions. That's way first call compiles and the second one doesnot.
My question is what does author mean in above statment "only if they are listed in the parameter list" ? What is parameter list?
When you write an operator, try to think of it in terms of an explicit function call.
Rational oneHalf(1, 2);
Rational result = oneHalf.multiply(2); // Ok, can convert
Rational result = 2.multiply(oneHalf); // OWAIT, no such function on int.
Since there is no such operator on an int, the compiler doesn't know how to handle oneHalf to make the call work, and throws an error. The "Parameter list" in this case is the argument to the operator. You need to make a free function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With