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; }

C++ Programming Objects and Classes Difficulty: Medium
Choose an option
  • A
    The program will print the output 1 2.
  • B
    The program will print the output 0 1.
  • C
    The program will print the output 1 1.
  • D
    The program will print the output 1.
  • E
    The 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:

  • 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.

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