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;
}- A. 2 1
- B. 3 3
- C. 2 2
- 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
- What is printed? java interface Shape { static double unit() { return 1.0; } double area(); } class Square implements Shape { double side…
- What is printed? cpp struct Counter { static int next() { static int n = 0; return ++n; } }; int main() { cout << Counter::next() <<…
- What is printed? cpp class Account { double balance; public: Account(double b) : balance(b) {} Account operator+(const Account &other)…
- What is printed? java class Base { public static void greet() { System.out.print("Base.greet "); } } class Sub extends Base { public…
- What is printed? cpp struct Base { void greet() { cout << "Base::greet "; } }; struct Sub : Base { void greet() { cout << "Sub::greet "; }…
- What is printed? cpp struct Base { static void hello() { cout << "Base::hello "; } }; struct Derived : Base { static void hello() { cout…