ProgrammingHardProduct-company placement · C++

Which line fails to compile?

Which line fails to compile?
struct P {
    int x = 3;
    ostream& operator<<(ostream& os) { return os << x; }
};
int main() {
    P p;
    cout << p;   // L1
    p << cout;   // L2
}
  1. A. L2 only
  2. B. L1 only
  3. C. Both
  4. D. Neither

Correct answer: B. L1 only

A member operator<< takes the object as its LEFT operand, so it is invoked as p << cout. cout << p would need a non-member operator<<(ostream&, const P&), which is why stream operators are written as free (often friend) functions.

More OOP with C++ and Java questions

Exams that ask this topic