ProgrammingHardProduct-company placement · C++

What is printed?

What is printed?
// C++17
struct Counter { int n = 0; int operator()() { return ++n; } };
int main() {
    Counter c;
    c(); c();
    Counter d = c;
    d();
    cout << c.n << d.n << c();
}
  1. A. 333
  2. B. 232
  3. C. 233
  4. D. 223

Correct answer: C. 233

d is a copy of c taken when c.n was 2, so they count independently: d() makes d.n = 3. Since C++17 the operands of << are evaluated left to right, so c.n (2) is read before c() returns 3.

More OOP with C++ and Java questions

Exams that ask this topic