ProgrammingHardProduct-company placement · C++

What is printed?

What is printed?
struct G { G() { cout << "G"; } ~G() { cout << "g"; } };
G g1;
int main() {
    cout << "M";
    static G s;
    cout << "m";
}
  1. A. MGGmgg
  2. B. GMGgmg
  3. C. GMGm
  4. D. GMGmgg

Correct answer: D. GMGmgg

The global g1 is constructed before main. The static local s is constructed when reached. At exit, objects with static storage are destroyed in reverse order of construction (s, then g1), so two g's follow m.

More OOP with C++ and Java questions

Exams that ask this topic