Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why return const Rational rather than Rational

Tags:

c++

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?
like image 976
q0987 Avatar asked Oct 21 '10 16:10

q0987


2 Answers

  1. So that you can't do something like Rational a, b, c; (a * b) = c;.

  2. No.

like image 85
Oliver Charlesworth Avatar answered Nov 11 '22 08:11

Oliver Charlesworth


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.

like image 29
fredoverflow Avatar answered Nov 11 '22 07:11

fredoverflow