Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream Operator Overloading

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

like image 283
josh Avatar asked Jul 23 '10 22:07

josh


People also ask

Can we overload stream insertion operator?

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.

What is a stream operator?

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.

What is stream insertion operator in C++?

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.

How is the stream extraction operator written in C++?

In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used for input.


2 Answers

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.

like image 61
CB Bailey Avatar answered Oct 05 '22 21:10

CB Bailey


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.

like image 34
Khaled Alshaya Avatar answered Oct 05 '22 23:10

Khaled Alshaya