ProgrammingHardMicrosoft/Google SDE MCQ · GATE CS

Which line fails to compile?

Which line fails to compile?
struct M {
    int v;
    M(int x) : v(x) { }
    M operator+(const M& o) const { return M(v + o.v); }
};
int main() {
    M a(1);
    M b = a + 2;      // line 1
    M c = 2 + a;      // line 2
    M d = a + a;      // line 3
}
  1. A. Line 1
  2. B. Line 3
  3. C. Line 2
  4. D. None of them

Correct answer: C. Line 2

A member operator+ needs an M on the left. In a + 2 the 2 converts to M through the non-explicit constructor, but in 2 + a no conversion is applied to the left operand for a member call, so it fails. A non-member operator+ would accept both.

More OOP with C++ and Java questions

Exams that ask this topic