ProgrammingHardMicrosoft/Google SDE MCQ · GATE CS

What is printed?

What is printed?
struct Counter {
    int n = 0;
    Counter& add(int k) { n += k; return *this; }
    Counter  addCopy(int k) { n += k; return *this; }
};
int main() {
    Counter c;
    c.add(1).add(2);
    c.addCopy(10).addCopy(20);
    cout << c.n;
}
  1. A. 33
  2. B. 13
  3. C. 3
  4. D. 11

Correct answer: B. 13

add returns a reference, so the chain keeps modifying c: n = 3. addCopy changes c (n = 13) but returns a copy, and the second addCopy(20) modifies only that temporary, so c.n is 13.

More OOP with C++ and Java questions

Exams that ask this topic