Re: Question on implicit type conversion
On 07.03.2012 20:06, Ruby Stevenson wrote:
I am reading Effective C++, item 24 on implicit type conversion. The
example given is that:
class Rational {
public:
Rational (int numerator=0, int denominator=1);
const Rational operator*(const Rational&rhs) const;
}
Rational oneHalf(1,2);
result = oneHalf * 2; // fine
result = 2 * oneHalf; //error
The book then says "It turns out that parameters are eligible for
implicit type conversion only if they are listed in the parameter
list" ...
I am confused as to what parameter list it is talking about??
In the first case '2' is implicitly converted to 'Rational', because the
left hand side operand of '*' is of type 'Rational' and that type has a
member function 'operator*' that requires the right hand side operand to
be of type 'Rational const&'.
In the second case the left hand side operand is '2', of type 'int'. The
only '*' operator associated with that type is the built-in '*'. The
built-in arithmetic operators like '*' do force some implicit
conversions, called "promotions", essentially bringing both operands up
to the same common supertype, but type `Rational` does not offer any
conversion to any of the built-in arithmetic types.
What if it did, though?
<code>
#include <iostream>
struct Rational
{
operator double() const { return 7; }
};
int main()
{
using namespace std;
cout << 6*Rational() << endl;
}
</code>
That works perfectly fine (according to the C++ standard, not just
according to a specific compiler), so the book is a bit misleading.
Cheers & hth.,
- Alf