Search code examples
c++memberfriend

My understanding of friend functions


Sometimes a non-member function may need access to the private members it's taking in as a agrument. A friend function is a non-member function that gives private access to the classes it's friends with.

Class X{
    int number;
public:
    X& operator+=(const X& rhs);//a += b is a.operator(b)
    friend int& operator+=(int& addthis, const X& rhs);//add this += b is I don't know what lol
}
X& operator+=(const X& rhs){
    this->number = this->number + rhs.number;        
}
int& operator+=(int& addthis, const X& rhs){
     addthis = addthis + rhs.number;
     return *this;
}

What I read is that if I wanted to do += to an object, object += int, just overload the += operator, but what if the int came before the object. Say int += object? Than I would have to write it as a friend function, and that's where I get a little lost. Why can't I just write int& operator+=(int& addthis, const X& hrs); as a member function? I assume a friend function can work with other classes since it's a non-member function, so it's not assigned to any specific class?

I'm sorry I just don't understand why I would use friend function over making it a member function. Really would appreciate any feedback, thank you.


Solution

  • Consider you implemented operator overloading as member function and performed something like x += y where both x and y are objects of the class which has the operator += overloaded.

    Compiler parses x += y as x.operator+=(y) which is fine as both operands x and y are of the same class which has the operator += overloaded.

    Now consider an expression like 2 += y (this may be insane, but I am trying explain why operator overloading with friend functions may be at time beneficial over operator overloading with member functions)

    Since, the expression 2 += y will be parsed by compiler as 2.operator+=(y), an error is raised. Maybe 2 may get converted to an object of the class using constructor for conversion; (Single argument constructors can be used for conversion) but that is not the point here.

    Using friend function to overload the operator calls the above expression 2 += y as operator+=(2, y) which works fine.