C++ static data member and constructor side effects: given exit(0) when x == 1, what does the program actually print?\n\n#include<iostream.h>\n#include<process.h>\nclass CuriousTab\n{\n static int x;\npublic:\n CuriousTab()\n {\n if (x == 1)\n exit(0);\n else\n x++;\n }\n void Display()\n {\n cout << x << " ";\n }\n};\nint CuriousTab::x = 0;\nint main()\n{\n CuriousTab objCuriousTab1;\n objCuriousTab1.Display();\n CuriousTab objCuriousTab2;\n objCuriousTab2.Display();\n return 0;\n}

Difficulty: Medium

Correct Answer: The program will print the output 1.

Explanation:


Introduction / Context:
This problem examines static data members shared across instances and program termination via exit(0) inside a constructor. It asks what output is produced before the process terminates.


Given Data / Assumptions:

  • x is a static int, initially 0.
  • First object increments x to 1.
  • Second object construction exits the program if x == 1.
  • Each Display() prints the current x value followed by a space.


Concept / Approach:
The first instance constructor sets x to 1, then prints 1. When the second instance is constructed, the condition x==1 is true and the program terminates immediately, preventing the second print.


Step-by-Step Solution:
Start: x=0.Construct first object ⇒ x becomes 1.Print via first Display() ⇒ output 1 .Begin constructing second object ⇒ condition true ⇒ exit(0) ⇒ program ends; no second output.


Verification / Alternative check:
Remove the exit(0) and observe two prints: 1 2. With exit(0) in place, only the first survives.


Why Other Options Are Wrong:
Options A/B/C assume the second construction completes or prints; it does not because the program exits in the constructor.


Common Pitfalls:
Expecting destructors or buffered output after exit(0); exit terminates without returning to main.


Final Answer:
The program will print the output 1.

More Questions from Objects and Classes

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion