ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
struct R { int v = 0; R& inc() { v++; return *this; } };
struct V { int v = 0; V  inc() { v++; return *this; } };
int main() {
    R r; V w;
    r.inc().inc().inc();
    w.inc().inc().inc();
    cout << r.v << " " << w.v;
}
  1. A. 1 1
  2. B. 3 3
  3. C. 3 1
  4. D. 1 3

Correct answer: C. 3 1

R::inc returns a reference, so each chained call works on r itself: 3. V::inc returns a copy, so only the first call touches w (v = 1); the next two increment temporary copies.

More OOP with C++ and Java questions

Exams that ask this topic