Can anybody explain why do you need to return a reference while overloading operators
e.g.
friend std::ostream& operator<< (std::ostream& out, const std::string& str)
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.
It is to make “chaining” of the operator work, in examples like this:
If the first (leftmost) use of the
operator<<()hadn’t returned a reference, there would not be an object to call for the second use of the operator.