ProgrammingModerateMicrosoft/Amazon SDE MCQ · GATE CS
What is printed?
What is printed?
struct N {
int v;
N& operator++() { v += 10; return *this; }
N operator++(int) { N t = *this; v += 1; return t; }
};
int main() {
N a{0};
N b = a++;
N c = ++a;
cout << a.v << " " << b.v << " " << c.v;
}- A. 11 1 11
- B. 11 0 11
- C. 11 0 10
- D. 20 0 11
Correct answer: B. 11 0 11
a++ calls the int overload: it returns the old value (b = 0) and adds 1 (a = 1). ++a adds 10, making a = 11, and c is copied from the returned reference, so c = 11.
More OOP with C++ and Java questions
- What is printed? cpp struct A { int x = 1; }; struct B : virtual A { B() { x += 10; } }; struct C : virtual A { C() { x += 100; } }…
- What is printed? cpp struct A { A(int v) { cout << v; } }; struct B : virtual A { B() : A(1) { } }; struct C : virtual A { C() : A(2) { }…
- What is printed? cpp struct V { V() { cout << 'V'; } }; struct X { X() { cout << 'X'; } }; struct M { M() { cout << 'm'; } }; struct D…
- What is printed? cpp struct R { R() { cout << "r"; } ~R() { cout << "~r"; } }; struct T { R r; T() { cout << "t"; throw 1; } ~T() { cout…
- What is printed? cpp struct E { virtual const char w() const { return "E"; } }; struct F : E { const char w() const override { return "F"…
- What is printed? cpp struct E { }; struct F : E { }; int main() { try { try { throw F(); } catch (E& e) { throw e; } } catch (F&) { cout…