ProgrammingHardProduct-company placement · C++

Which line fails to compile?

Which line fails to compile?
// C++17
struct S {
    int v;
    S(int x) : v(x) { }
    bool operator==(const S& o) const { return v == o.v; }
};
int main() {
    S s(1);
    bool a = (s == 1);   // L1
    bool b = (1 == s);   // L2
}
  1. A. L1 only
  2. B. Both
  3. C. Neither
  4. D. L2 only

Correct answer: D. L2 only

For a member operator the left operand must already be an S; no implicit conversion is applied to it. In s == 1 the right operand converts via S(int). A non-member (friend) operator== allows conversions on both sides.

More OOP with C++ and Java questions

Exams that ask this topic