Why should overloading of stream operators(<<,>>) be kept as friends rather than making them members of the class?
The stream insertion and stream extraction operators also can be overloaded to perform input and output for user-defined types like an object. Here, it is important to make operator overloading function a friend of the class because it would be called without creating an object.
A stream operator can be invoked to transform input streams to output streams. SPL supports two kinds of operators: primitive operators and composite operators. A primitive operator is written in C++ or Java™, whereas a composite operator is written in SPL and contains a reusable stream subgraph.
The insertion ( << ) operator, which is preprogrammed for all standard C++ data types, sends bytes to an output stream object. Insertion operators work with predefined "manipulators," which are elements that change the default format of integer arguments.
In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used for input.
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.
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.
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