Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implementing operator * in C++

Tags:

c++

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?

like image 640
venkysmarty Avatar asked Jul 26 '26 11:07

venkysmarty


1 Answers

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.

like image 188
Puppy Avatar answered Jul 28 '26 00:07

Puppy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!