why are friends used?

Nov 2, 2009 at 4:05am
in overloading operators when set and get can be used in its place other than for performance reasons?
Nov 2, 2009 at 4:46am
I think you miss the point of operator overloading.
Nov 2, 2009 at 5:22am
can you share some light as to why that is the case?
Nov 2, 2009 at 5:36am
I was thinking in my mind, if given any class, say for example:
1
2
3
4
5
class MyClass
{
    int a;
    double b;
};


how awkward it would be to add two objects of MyClass together using get and set
functions - rather than using function overloading and saying
1
2
MyClass a,b,c;
c = a+b


or something like:

1
2
MyClass a,b,c,d,e,f,g;
MyClass m = a+b+c+d+e+f+g


Or maybe I misunderstand the question. Maybe you can give an example using set and get functions.
Nov 2, 2009 at 6:07am
I think he meant something like:

1
2
3
Obj& operator+ (const Obj& o1, const Obj& o2) {
    return Obj(o1.a()+o2.a());
}


Instead of friending the operator+ and just doing something like:
1
2
3
Obj& operator+ (const Obj& o1, const Obj& o2) {
    return Obj(o1._a+o2._a);
}
Nov 2, 2009 at 8:39am
Providing a get/set methods for a class is usually a bad idea:

http://www.parashift.com/c++-faq-lite/friends.html#faq-14.2

I just consider an overloaded global operator to be a member of a class. With this assumption, why not make it a friend and access members of the class directly?
Topic archived. No new replies allowed.