ProgrammingVery hardProduct company interview · GATE level
What is printed?
What is printed?
struct C {
static int n;
C() { n++; }
~C() { n--; }
};
int C::n = 0;
void f(C c) { }
int main() {
C a;
f(a);
f(a);
{ C b = a; }
cout << C::n;
}- A. -2
- B. 1
- C. 0
- D. -1
Correct answer: A. -2
Only the default constructor increments n. The by-value parameter of f and the local b are made by the implicitly generated copy constructor, which does not touch n, but each of them is later destroyed and its destructor decrements n. a: n = 1; two calls of f: n = -1; the block with b: n = -2 (a itself is destroyed only after the print). The fix is a user-written copy constructor that also increments n.
More OOP with C++ and Java questions
- What is printed? cpp struct S { void f() { cout << "N"; } void f() const { cout << "C"; } }; void call(const S& s) { s.f(); } int main() {…
- What is printed? cpp struct B { void f(int) { cout << "Bi "; } void f(double) { cout << "Bd "; } }; struct D : B { using B::f; void f(int)…
- What happens with this code? cpp class B { public: virtual void f() { cout << "B"; } }; class D : public B { private: void f() override {…
- What is printed? cpp struct B { virtual const char who() const { return "B"; } }; struct D : B { const char who() const override { return…
- What is printed? cpp struct A { int v = 0; A() { cout << "A"; } }; struct B : A { B() { cout << "B"; } }; struct C : A { C() { cout <<…
- What is printed? cpp void f(bool) { cout << "bool "; } void f(std::string) { cout << "string "; } void g(int) { cout << "int "; } void…