ProgrammingHardTCS NQT · Infosys interview pattern

What is printed?

What is printed?
struct V {
    int x;
    V(int a) : x(a) {}
    V operator+(const V& o) const { return V(x + o.x * 2); }
};
int main() {
    V a(1), b(2), c(3);
    cout << (a + b + c).x;
}
  1. A. 17
  2. B. 6
  3. C. 11
  4. D. 9

Correct answer: C. 11

+ is left-associative: (a + b) = V(1 + 2 × 2) = V(5); then V(5) + c = V(5 + 3 × 2) = V(11). Grouping a + (b + c) gives 1 + 8 × 2 = 17, ignoring the × 2 gives 6, and doubling only the last operand gives 1 + 2 + 6 = 9.

More OOP with C++ and Java questions

Exams that ask this topic