ProgrammingHardGATE CS · TCS NQT Prime · Product Company SDE

Why is `operator<<` for printing a user-defined type usually written as a free function (often declared a friend), rather than as a member function of that type?

  1. A. Free functions always run faster than member functions
  2. B. Its left-hand operand is a std::ostream&, not an object of the user's class, so it cannot be a member of that class
  3. C. The compiler rejects member-function stream operators outright
  4. D. Member functions are not allowed to access private data

Correct answer: B. Its left-hand operand is a std::ostream&, not an object of the user's class, so it cannot be a member of that class

A member operator's implicit first (left) operand must be the class type itself; since std::cout << obj puts the stream on the left, the operator must be free (or a member of ostream), hence the usual friend-function pattern.

More OOP with C++ and Java questions

Exams that ask this topic