ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
struct Logger {
    static int instances;
    Logger() { instances++; }
    ~Logger() { instances--; }
};
int Logger::instances = 0;
void work() {
    Logger a;
    {
        Logger b;
        cout << Logger::instances << " ";
    }
    cout << Logger::instances << " ";
}
int main() {
    work();
    cout << Logger::instances;
}
  1. A. 2 1 0
  2. B. 1 2 0
  3. C. 2 1 1
  4. D. 2 2 0

Correct answer: A. 2 1 0

a is created (instances=1); entering the inner block creates b (instances=2), printed as 2. Leaving that scope destroys b (instances=1), printed as 1. work() returning destroys a too (instances=0), so main's own print shows 0. Output: 2 1 0.

More OOP with C++ and Java questions

Exams that ask this topic