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<
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.