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

c++, friend-function, iostream, operator-overloading

Solution

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

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.

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.

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.

Problem

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; } ``` - Can anyone explain (on a basic level) why we have to use a friend function declaration here? - Why do we have to pass all arguments and the return type of the operator by reference? - 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?

Original source

Related problems