ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
struct Base {
static int count;
Base() { count++; }
};
int Base::count = 0;
struct Derived : Base {};
int main() {
Derived d1, d2;
Base b1;
cout << d1.count << " " << Derived::count << " " << Base::count;
}- A. 2 3 3
- B. 3 3 3
- C. 2 2 3
- D. 3 2 3
Correct answer: B. 3 3 3
static int count is one shared variable; Derived inherits it rather than getting its own copy. Three Base constructors run in total (d1, d2, b1), so count becomes 3, and every access path (through an object, through Derived::, through Base::) reads the same shared value.
More OOP with C++ and Java questions
- What is printed? cpp struct Animal { void speak() { cout << "..."; } }; struct Dog : Animal { void speak() { cout << "Woof"; } }; int…
- What is printed? (function-local static) cpp int next() { static int n = 0; return ++n; } int main() { cout << next() << next() << next()…
- What is printed? java class A { void greet() { System.out.print("A-inst "); } static void greet(int x) { System.out.print("A-static "); }…
- What is printed? cpp class Base { public: void info() { cout << "Base::info "; helper(); } void helper() { cout << "Base::helper"; } }…
- What is printed? cpp struct A { int v = 1; virtual void show() { cout << v; } }; struct B : A { int v = 2; void show() override { cout <<…
- What is printed? cpp struct Base { virtual void f() { cout << "Base-f "; g(); } void g() { cout << "Base-g"; } }; struct Derived : Base {…