ProgrammingVery hardMicrosoft/Google SDE MCQ · GATE CS

What is printed?

What is printed?
struct T {
    int id;
    T(int i) : id(i) { cout << "+" << id; }
    ~T() { cout << "-" << id; }
};
T g(1);
void f() { static T s(2); }
int main() {
    T m(3);
    f();
    f();
}
  1. A. +1+3+2-3-2-1
  2. B. +1+3+2+2-3-2-2-1
  3. C. +1+3+2-3-1-2
  4. D. +1+2+3-3-2-1

Correct answer: A. +1+3+2-3-2-1

g is built before main, m when main starts, and the static local s on the first call of f only. m dies when main returns; then static-storage objects are destroyed in reverse order of construction: s (built later) before g.

More OOP with C++ and Java questions

Exams that ask this topic