Search code examples
c++operator-overloadingiostreamfriend-function

Using friend functions for I/O operator overloading in c++


I am learning c++ on my own. I was studying operator overloading, i was able to understand addition and subtraction operator overloading. But overloading of I/O operators is a bit confusing. I have created a class for Complex numbers, now i am overloading operators.

Function prototype from Complex.h

friend ostream& operator<<(ostream&, const Complex&);

Function from Complex.cpp

ostream& operator<<(ostream& os, const Complex& value){
os << "(" << value.r <<", "
<< value.i << ")" ;
return os;
}
  1. Can anyone explain (on a basic level) why we have to use a friend function declaration here?
  2. Why do we have to pass all arguments and the return type of the operator by reference?
  3. This function works fine without using const, but why are we using const here? What is the advantage of passing Complex as a constant reference?

Solution

  • For friend ostream& operator<<(ostream&,const Complex&); :

    1. Because you declare a free function here, and would like it to access the internals (private/protected) of your Complex objects. It is very common to have "friend free functions" for those overloads, but certainly not mandatory.

    2. Because streams are non copyable (it does not make sense, see also this post), passing by value would require a copy. Passing Complex by value would also require a useless copy.

    3. Because those output operators are not supposed to modify the objects they are working on (Input operators are, obviously), so add const to ensure that.