2

As per Deitel's 9ed C++ How to program, p. 444:

Why Overloaded Stream Insertion and Stream Extraction Operators Are Overloaded as Non-Member Functions

The overloaded stream insertion operator (<<) is used in an expression in which the left operand has type ostream &, as in cout << classObject. To use the operator in this manner where the right operand is an object of a user-defined class, it must be overloaded as a nonmember function. To be a member function, operator << would have to be a member of class ostream. This is not possible for user-defined classes, since we are not allowed to modify C++ Standard Library classes.

The thing is << is already a member of ostream. What exactly is it talking about? Am I missing something?

=================================================================

OK, looking back to p. 440:

Overloaded operator functions for binary operators can be member functions only when the left operand is an object of the class in which the function is a member.

And << is already a member of ostream, and since redefinition of C++ STL classes is not allowed, << must be overloaded as a non-member function. In short, the wording in Deitel's is confusing.

J. Doe
  • 441
  • 1
  • 4
  • 13

1 Answers1

0

For a user-defined class you cannot add another overloaded member function operator<<() into ostream. Thus you must use the non-member function style of operator overloading to support the user defined class.

std::ostream& operator<<(std::ostream& os, const MyClass& rhs);
timrau
  • 22,578
  • 4
  • 51
  • 64
  • If I define an overload for `operator<<()` in my own class, it is pushed into `ostream` too? I thought it was kept for the class only. Can you clarify? – J. Doe Apr 15 '18 at 03:18
  • No, your overload is not pushed into `ostream`. In my answer the function `operator<<()` does _not_ belong to any class. – timrau Apr 15 '18 at 03:43