ProgrammingVery hardTCS NQT Prime · Infosys SP

What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std)

What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std)
struct I {
    int v;
    I& operator++() { ++v; return *this; }
    I operator++(int) { I t = *this; ++v; return t; }
};
int main() {
    I a{5};
    I b = a++;
    I c = ++a;
    cout << a.v << b.v << c.v;
}
  1. A. 757
  2. B. 665
  3. C. 577
  4. D. 767

Correct answer: A. 757

a++ returns the old copy (b.v = 5) and a becomes 6; ++a makes a = 7 and c copies it (7). Output a.v, b.v, c.v = 7,5,7.

More OOP with C++ and Java questions

Exams that ask this topic