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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With