ProgrammingHardProduct-company placement · GATE CS

Which lines fail to compile?

Which lines fail 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;   // L1
    M c = 2 + a;   // L2
    M d = a + a;   // L3
}
  1. A. L1 only
  2. B. L2 only
  3. C. L1 and L2
  4. D. None

Correct answer: B. L2 only

For a member operator the left operand must already be an M; implicit conversions apply only to the argument. So a + 2 converts 2 through M(int), but 2 + a finds no operator. Writing operator+ as a non-member friend makes both work.

More OOP with C++ and Java questions

Exams that ask this topic