Operator Overloading Using a Friend Function

What is the role of friend function in this program? Is it even executed here?
Thanks,
pintu

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
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
using namespace std;
class loc {
int longitude, latitude;
public:
loc() {} // needed to construct temporaries
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}
void show() {
cout << longitude << " ";
cout << latitude << "\n";
}
friend loc operator+(loc op1, loc op2); // now a friend
loc operator-(loc op2);
loc operator=(loc op2);
loc operator++();
};
// Now, + is overloaded using friend function.
loc operator+(loc op1, loc op2)
{
loc temp;
temp.longitude = op1.longitude + op2.longitude;
temp.latitude = op1.latitude + op2.latitude;
return temp;
}
// Overload - for loc.
loc loc::operator-(loc op2)
{
loc temp;
// notice order of operands
temp.longitude = longitude - op2.longitude;
temp.latitude = latitude - op2.latitude;
return temp;
}
// Overload assignment for loc.
loc loc::operator=(loc op2)
{
longitude = op2.longitude;
latitude = op2.latitude;
return *this; // i.e., return object that generated call
}
// Overload ++ for loc.
loc loc::operator++()
{
longitude++;
latitude++;
return *this;
}
int main()
{
loc ob1(10, 20), ob2( 5, 30);
ob1 = ob1 + ob2;
ob1.show();
return 0;
}
The friend declaration gives operator+(loc, loc) access to the private members of loc. If it wasn't a friend it wouldn't be allowed to access longitude and latitude because they are private.
the friend declaration in the class allows the function loc operator+(loc op1, loc op2) (this isn't part of the class!!) to access the nonPublic fields of loc (latitude and longitude). Try to comment out the friend line, and your compiler will complain, that latitude and longitude aren't accessible from this context or so.

PS: if you are going to use this class, you should take a look at there: http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html
There are a few guidlines for operator overloading which makes your classes behave more like built in types.

PPS: too slow :)
Last edited on
Topic archived. No new replies allowed.