Practice mode C++

Why is operator<< for printing a user-defined type to std::ostream usually written as a non-member (often friend) function?

Correct answer B. Because the left operand is the ostream, not an object of the user's class

Explanation

A member operator always takes its own class as the left operand, so a member operator<< would require writing obj << cout. For cout << obj the left operand is std::ostream, which you cannot modify, so the operator is written as a free function taking (std::ostream&, const T&). It is made a friend only when it needs access to private members.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.