Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why friend function is preferred to member function for operator<<

When you are going to print an object, a friend operator<< is used. Can we use member function for operator<< ?

class A {

public:
void operator<<(ostream& i) { i<<"Member function";}
friend ostream& operator<<(ostream& i, A& a) { i<<"operator<<"; return i;}
};


int main () {

   A a;
   A b;
   A c;
   cout<<a<<b<<c<<endl;
   a<<cout;
  return 0;
}

One point is that friend function enable us to use it like this

cout<<a<<b<<c

What other reasons?

like image 718
skydoor Avatar asked Mar 16 '10 21:03

skydoor


1 Answers

You have to use a free function and not a member function as for binary operators the left hand side is always *this for member functions with the right hand side being passed as the other parameter.

For output stream operators the left hand side is always the stream object so if you are streaming to a standard class and not writing the stream yourself you have to provide a free function and not a member of your class.

Although it would be possible to provide a backwards stream operator as a member function and stream out like this:

myObject >> std::cout;

not only would you violate a very strong library convention, as you point out, chaining output operations would not work due to the left-to-right grouping of >>.

Edit: As others have noted, while you have to make it a free function it only needs to be a friend if the streaming function cannot be implemented in terms of the class' public interface.

like image 158
CB Bailey Avatar answered Oct 10 '22 11:10

CB Bailey