ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
struct Logger {
    Logger(string tag) : tag(tag) { cout << "open-" << tag << " "; }
    ~Logger() { cout << "close-" << tag << " "; }
    string tag;
};
void process() {
    Logger l1("outer");
    {
        Logger l2("inner");
        cout << "work ";
    }
    cout << "more ";
}
int main() { process(); }
  1. A. open-outer open-inner work close-inner more close-outer
  2. B. open-outer open-inner work more close-inner close-outer
  3. C. open-inner open-outer work close-outer close-inner more
  4. D. open-outer open-inner work close-outer close-inner more

Correct answer: A. open-outer open-inner work close-inner more close-outer

l1 is constructed first. Entering the inner block constructs l2 (open-inner), work prints, and leaving that inner scope immediately destroys l2 (close-inner) via RAII before "more" prints. l1 is only destroyed when process() itself returns, after "more" is printed, giving close-outer last.

More OOP with C++ and Java questions

Exams that ask this topic