ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
struct Counter {
static int next() { static int n = 0; return ++n; }
};
int main() {
cout << Counter::next() << Counter::next() << Counter::next();
}- A. 111
- B. 123
- C. 000
- D. Compile-time error: a static member function cannot contain a local static variable
Correct answer: B. 123
The local static variable n is initialised only once and persists across calls, shared by every invocation of next() regardless of which object (or none) calls it. Each call increments and returns it: 1, then 2, then 3, giving 123.
More OOP with C++ and Java questions
- 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…
- What is printed? java class Outer { static int x = 100; static class Nested { int x = 200; void show() { System.out.println(x + " " +…
- What is printed? cpp class Singleton { static Singleton instance; Singleton() { cout << "Created "; } public: static Singleton get() { if…