ProgrammingHardMicrosoft/Amazon SDE MCQ · GATE CS
What is printed?
What is printed?
struct C {
static int n;
C() { ++n; }
C(const C&) { ++n; }
~C() { --n; }
};
int C::n = 0;
void f(C c) { cout << C::n; }
int main() {
C a;
f(a);
cout << C::n;
{ C b[3]; cout << C::n; }
cout << C::n;
}- A. 2141
- B. 1141
- C. 2131
- D. 2241
Correct answer: A. 2141
Inside f the copied parameter makes n = 2; after the call it is destroyed (n = 1). The array adds 3 (n = 4) and its destruction at the brace takes n back to 1.
More OOP with C++ and Java questions
- What is printed? cpp struct N { int v; N& operator++() { v += 10; return this; } N operator++(int) { N t = this; v += 1; return t; } }…
- 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"…