ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Logger {
public:
    static int instances;
    Logger() { instances++; }
    ~Logger() { instances--; }
};
int Logger::instances = 0;
void createTemp() {
    Logger temp;
    cout << Logger::instances << " ";
}
int main() {
    Logger l1;
    createTemp();
    cout << Logger::instances;
}
  1. A. 2 1
  2. B. 1 1
  3. C. 2 2
  4. D. 1 2

Correct answer: A. 2 1

l1 is constructed first: instances=1. createTemp() constructs its own local temp, bumping instances to 2, printed inside the function ("2 "); when createTemp() returns, temp goes out of scope and its destructor runs, decrementing back to 1, which main then prints ("1").

More OOP with C++ and Java questions

Exams that ask this topic