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(); }- A. open-outer open-inner work close-inner more close-outer
- B. open-outer open-inner work more close-inner close-outer
- C. open-inner open-outer work close-outer close-inner more
- 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
- What is printed? java class A { A() { this(10); System.out.print("A() "); } A(int x) { System.out.print("A(int)=" + x + " "); } } public…
- What is printed? cpp struct Base { Base() { cout << "Base() "; } Base(int x) { cout << "Base(int) "; } }; struct Derived : Base {…
- What is printed? java class Resource { Resource() { System.out.print("open "); throw new RuntimeException("ctor failed"); } void close() {…
- What is printed? cpp struct Base { virtual ~Base() { cout << "~Base "; } }; struct Mid : Base { ~Mid() { cout << "~Mid "; } }; struct Leaf…
- What is printed? java class Animal { Animal() { System.out.print(category() + " "); } String category() { return "Animal"; } } class Bird…
- What is printed? cpp struct Base { Base() { cout << "Base "; } Base(const Base&) { cout << "BaseCopy "; } }; struct Derived : Base {…