Now as you mentioned passing argouments by reference. a is indeed passed by reference and changing a.x or any a's element would actually change the incoming paramet on outer scope yes? |
If that were allowed, yes. However, the parameter is declared as
const
, which means the compiler will reject any attempt to modify that parameter.
An important reason for the & in the return type of the function is to allow the chaining of operations.
I came up with a rather contrived example - I'm sure there are better ones.
Here there is a user-defined type
Number
which aims to behave in a very similar manner to the built-in numeric types - though this code is not thorough and complete.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream>
class Number {
double value;
public:
Number() : value(0.0) { }
Number(double n) : value(n) { }
Number & operator+=(const Number & n)
{
value += n.value;
return *this;
}
Number & operator*=(const Number & n)
{
value *= n.value;
return *this;
}
friend std::ostream & operator << (std::ostream & os, const Number & n)
{
return os << n.value;
}
};
int main()
{
{
double a = 2;
double b = 3;
double c = 5;
double d = 7;
((d += b) *= a) += c;
std::cout << "type double:\n" << " d = " << d << '\n';
}
{
Number a = 2;
Number b = 3;
Number c = 5;
Number d = 7;
((d += b) *= a) += c;
std::cout << "type Number:\n" << " d = " << d << '\n';
}
}
|
The rather unsightly-looking expression at lines 34 and 43 chains a series of operations, one after the other.
1.
d += b
the result of 7 +3 is calculated, and assigned to
d
2.
*= a
the current value of d (10) is multiplied by 2 and the result stored in d.
3.
+= c
the current value of d (20) is added to 5 and the result stored in d.
Final result d = 25.
However, if either or both of the
&
are omitted in the function definitions at lines 9 and 15, instead of the later operations modifying d, they instead operate on a temporary variable instead, giving a different result.
Sorry if this example a bit confusing.