ProgrammingVery hardProduct-company placement · 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);
{ C b[3]; cout << C::n; }
cout << C::n;
}- A. 141
- B. 242
- C. 241
- D. 251
Correct answer: C. 241
Passing by value copy-constructs the parameter, so f prints 2; the parameter is destroyed before the next statement (n = 1). The array adds 3 (prints 4) and its elements are destroyed at the closing brace, leaving 1. 141 forgets the copy constructor.
More OOP with C++ and Java questions
- What is printed (C++17)? cpp int a[] = {1, 2, 3, 4}; int p = a + 1; cout << p++; cout << ++p; cout << p[-1];
- What is printed? cpp struct B { void f(int) { cout << "Bi"; } void f(const char) { cout << "Bs"; } }; struct D1 : B { void f(double) {…
- Which lines fail to compile? cpp struct B { void f() { } }; class D1 : B { }; struct D2 : B { }; class D3 : public B { }; int main() { D1…
- What is printed? cpp template <class T> void f(T) { cout << "T"; } template <class T> void f(T) { cout << "P"; } void f(int) { cout <<…
- What is printed? cpp struct S { void f() { cout << "N"; } void f() const { cout << "C"; } }; int main() { S a; const S b{}; const S& r =…
- What is printed? cpp int a = 1, b = 2; int& r = a; r = b; r = 5; cout << a << b;