C++ static data member and constructor side effects: given exit(0) when x == 1, what does the program actually print?
#include
#include
class CuriousTab
{
static int x;
public:
CuriousTab()
{
if (x == 1)
exit(0);
else
x++;
}
void Display()
{
cout << x << " ";
}
};
int CuriousTab::x = 0;
int main()
{
CuriousTab objCuriousTab1;
objCuriousTab1.Display();
CuriousTab objCuriousTab2;
objCuriousTab2.Display();
return 0;
}
-
AThe program will print the output 1 2.
-
BThe program will print the output 0 1.
-
CThe program will print the output 1 1.
-
DThe program will print the output 1.
-
EThe program will report compile time error.
Answer
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:
xis a staticint, initially 0.- First object increments
xto 1. - Second object construction exits the program if
x == 1. - Each
Display()prints the currentxvalue 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.