Why should overloading of stream operators(<<,>>) be kept as friends rather than making them members of the class?
Why should overloading of stream operators(<<,>>) be kept as friends rather than making them
Share
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.
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.