overloading << why as a friend?

Hi guys,

have been meaning to ask this question for a long time,I have done some research and seen some articles on stackoverflow but still can't seem to figure out why we must make operator<< a friend function instead of a member function

so why wouldn't it be possible to do it this way

1
2
3
4
5
6

  ostream& operator<<(ostream& os){

      os << variable << endl;
   }
 


instead we have to do it like

1
2
3
4
5
6
7


  friend ostream& operator<<(ostream& os,Object& obj){

      os << obj.variable << endl;
   }



thanks
When defining an operator as member function the first argument is always of the class type where you defined the operator. Since you want the ostream to be the first argument you would have to define the operator inside the ostream class but that is not possible so you are forced to define it as a non-member function.
Last edited on
but still can't seem to figure out why we must make operator<< a friend function instead of a member function


Well actually you don't always need or want the operator<< to be a friend function. The only time you must use a friend function is when you want the operator<< to be able to access the private members of the class. But if your class has public access member functions you can make the overload a non-member, non-friend function and use the public member functions to access the required private variables.



1
2
3
4
5
6
7
// Function in the global scope.
ostream& operator<<(ostream& os, Object& obj){

      os << obj.access_function();

     return os;  // Don't forget to return the stream like you promised.
   }


Topic archived. No new replies allowed.