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?
- A. Free functions always run faster than member functions
- 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
- C. The compiler rejects member-function stream operators outright
- 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
- java class R implements AutoCloseable { public void close() { System.out.print("close"); } } try (R r = new R()) {…
- Which statement about C++ vtables is correct for a class with multiple virtual functions?
- Class A's constructor declares throws IOException. Class B extends A. What must every constructor of B do about this checked exception?
- What access modifier and finality does a field declared directly inside a Java interface implicitly have?
- java Function<Integer,Integer> sq = x -> x x; Function<Integer,Integer> addOne = x -> x + 1; Function<Integer,Integer> combo =…
- What does the 'Rule of Five' in modern C++ say?