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

Posted by skydoor on Stack Overflow See other posts from Stack Overflow or by skydoor
Published on 2010-03-16T21:57:26Z Indexed on 2010/03/16 22:01 UTC
Read the original article Hit count: 208

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about c++

Related posts about operator-overloading