tags:

views:

86

answers:

2

I saw the following implementation of the operator* as follows:

class Rational {
public: 
       Rational(int numerator=0, int denominator=1);
       ...
private:
       int n, d; // numerator and denominator
       friend const Rational operator*(const Rational& lhs, const Rational& rhs)
      { 
          return Rational(lhs.n * rhs.n, lhs.d * rhs.d); 
      }    
};

I have two questions here:

  • Q1> why the operator* has to return const Rational rather than simply Rational
  • Q2> when we define a friend function, should we care about the access modifier?
+9  A: 
  1. So that you can't do something like Rational a, b, c; (a * b) = c;.

  2. No.

Oli Charlesworth
Hello Oli, thank you very much
q0987
Concise, informative, accurate. Good answer.
David Thornley
+5  A: 

Note that returning const Rational instead of Rational not only prevents nonsensical assignments but also move semantics (because Rational&& does not bind to const Rational) and is thus not recommended practice anymore in C++0x.

Scott Meyers wrote a note on this matter:

Declaring by-value function return values const will prevent their being bound to rvalue references in C++0x. Because rvalue references are designed to help improve the efficiency of C++ code, it's important to take into account the interaction of const return values and the initialization of rvalue references when specifying function signatures.

FredOverflow
Matthieu M.
@Mat: Although it's rather unlikely that `Rational` has any external resources, but think `string` or similar types and my argument is valid :)
FredOverflow
@FredOverflow: I agree, actually I was trying to extend your answer with an example of when move semantics would apply :)
Matthieu M.