0
friend ostream& operator<<(ostream& os, MyClass& obj);

I have e few questions:
1. Why do I need to write 'friend'?
2. Why do I need to write '&' before 'operator', 'os' and 'obj'?

Syperia
  • 94
  • 7
  • 1
    Sort of duplicate of http://stackoverflow.com/questions/236801/should-operator-be-implemented-as-a-friend-or-as-a-member-function – SteveMc May 26 '11 at 16:19

2 Answers2

0

The & in MyClass& makes the function take a reference to a MyClass object, not the object itself. (Similarly for the others.)

References are lightweight to pass around, and any change you make to the obj affects the original object. Without the & you would be instructing the compiler to construct a whole new MyClass in the call, destroy it on return and throw away any changes you might have made to its internal state.

The return of an ostream& is conventionally used to return the same ostream& that was passed in so you can write chains of shifts like cout << "hello " << 42 << endl; and have them behave the way you expect. (You could have it return something different - C++ makes it easy to completely mess with people's expectations - but don't do that.)

crazyscot
  • 11,819
  • 2
  • 39
  • 40
0

. Why do I need to write 'friend'?

ostream changes the left argument(alters the stream’s state), and hence as per general operator overloading semantics it should be implemented as member of left operand type. However, its left operand is a stream from the standard library, when you implement the output and input operations for your own type, you cannot change the standard library’s stream types. That’s why you need to implement these operators for your own types as non-member functions.

Alok Save
  • 202,538
  • 53
  • 430
  • 533