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’?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
&inMyClass&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
objaffects the original object. Without the&you would be instructing the compiler to construct a whole newMyClassin 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 likecout << "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.)