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() {
    Base b1, b2;
    Derived d1;
    cout << Base::count << " " << Derived::count;
}
  1. A. 2 1
  2. B. 3 3
  3. C. 2 2
  4. D. 3 1

Correct answer: B. 3 3

Derived does not declare its own count; it shares Base's single static count. Each of the three constructions, b1, b2, and d1 (whose Base subobject also runs Base's constructor), increments the same shared counter to 3, and Derived::count is just another name for the same variable, so both print 3.

More OOP with C++ and Java questions

Exams that ask this topic