views:

70

answers:

3

Why should overloading of stream operators(<<,>>) should be kept as friends rather than making them members of the class?

A: 

Members of what class? What is the type of the left-hand operand?

They don't have to be friend, though, unless there's a need to access otherwise unaccessible private data.

UncleBens
+5  A: 

When you overload a binary operator as a member function of a class the overload is used when the first operand is of the class type.

For stream operators, the first operand is the stream and not (usually) the custom class.

For this reason overloaded stream operators for custom classes which are designed to be used in the conventional manner can't be member functions of the custom class, they must be free functions.

(I'm assuming that the stream classes are not open to be changed; if they were you could add member functions to stream classes to cope with additional custom types but this would usually be undesirable from a dependency point of view.)

Whether or not they are friends should depend on whether they need access to non-public members of the class.

Charles Bailey
I think this is a bit misleading. They *can* be member functions, but to use them the usual way (writing to streams), they need to be member functions.
Tamás Szelei
@sztomi: I don't understand your comment. No, they don't _need_ to be member functions; they _can't_ be member functions (unless you're writing a stream class or writing your streaming operators backwards from the rest of the world).
Charles Bailey
So yes, they can be member functions. If you want them to work as usual (like the rest of the word uses it), you have to define them as friends. That's what I meant.
Tamás Szelei
@sztomi: I still don't understand what you mean. You don't have to declare them as friends, it's fine to have them as non-friend free functions if they can do there work with just the public interface of the custom class.
Charles Bailey
Before you edited you answer, it stated they "have to be" free function. No, they don't, only if you want them to work the usual way. I can't reword this any more. But this is really not a big deal, so forget it :).
Tamás Szelei
@sztomi: I edited for clarity; originally I was assuming the premise of the previous paragraph: that the first operand is the stream. Now I've made that explicit. In your first comment you said: "... they need to be member functions"; in your second comment you said that "If you want them to work as usual .... you have to define them as friends". Neither of these statements are true. I'm sorry if my answer wasn't 100% clear but I think that it's accurate.
Charles Bailey
+2  A: 

So you can say:

some_stream << my_class;

Note that the definition of member operators makes the left hand side the class it self. e.g.:

my_class << some_stream;

Which is not how the standard streams are supposed to work.

AraK