Why does operator+ takes its left operand by copy rather than by const reference?

inline X operator+(X lhs, const X& rhs)
{
lhs += rhs;
return lhs;
}

Why does operator+ takes its left operand by copy rather than by const reference?
So that it can be implemented in terms of += without first having to explicitly make a copy of lhs, as += itself modifies it's left-hand side.
lhs += rhs;


If lhs were a const &, you wouldn't be able to do that!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

class T{
public:
	int a;
	double d;		  
  	T(){}
  	T(int aa, double dd) : a(aa), d(dd) {}  	
};

T operator+ (const T &a1, const T &a2){
	return T(a1.a+a2.a , a1.d+a2.d);
}

int main () {
	T p(1,3.17);
	T q(7,0.16);	
	T r= p+q;
	std::cout << r.a << " " << r.d << "\n";	 
return 0;    
}
@anup30: if you've got `+' you may want to have `+=' (as you have with a lot of other types)
`+=' may be more efficient implement it, as you don't need a third object, and so `+' uses `+=' to avoid code duplication.
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
#include <iostream>

class T{
public:
	int a;
	double d;		  
  	T(){}
  	T(int aa, double dd) : a(aa), d(dd) {}  	
};

T operator+ (const T &a1, const T &a2){
	return T(a1.a+a2.a , a1.d+a2.d);
}

void operator+= (T &t1, const T &t2){
	t1.a += t2.a;
	t1.d += t2.d;
}

int main () {
	
	T p(1,3.17);
	T q(7,0.16);
	
	T r= p+q;
	std::cout << r.a << " " << r.d << "\n";
	
	p+=r;
	std::cout << p.a << " " << p.d << "\n";
	 
return 0;    
}
as I said ``avoid code duplication''
how is the duplication ?
You list all the member variables on line 12 and again on lines 16-17.

aseemgoyal did already show the necessary code for operator+ -- no members mentioned at all.
Topic archived. No new replies allowed.