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;
}
  1. A. 2 3 3
  2. B. 3 3 3
  3. C. 2 2 3
  4. 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

Exams that ask this topic