C++ static data and static member functions: after setting x via a class-qualified call, what is printed?\n\n#include<iostream.h>\nclass CuriousTab\n{\n static int x;\n public:\n static void SetData(int xx)\n {\n x = xx;\n }\n static void Display()\n {\n cout<< x;\n }\n};\nint CuriousTab::x = 0;\nint main()\n{\n CuriousTab::SetData(44);\n CuriousTab::Display();\n return 0;\n}

Difficulty: Easy

Correct Answer: The program will print the output 44.

Explanation:


Introduction / Context:
This item verifies knowledge of static data members and static member functions in C++. Static members belong to the class, not to any instance, and can be accessed with the class scope operator.


Given Data / Assumptions:

  • CuriousTab::x is defined and initialized to 0 outside the class.
  • SetData(44) stores 44 into the static x.
  • Display() prints the current value of x.


Concept / Approach:
A static data member has exactly one instance for the entire class. Static member functions may read and write it without any object. After assignment, all calls see the updated value.


Step-by-Step Solution:
1) Initialization: int CuriousTab::x = 0; sets starting value. 2) CuriousTab::SetData(44); writes 44 into the same static storage. 3) CuriousTab::Display(); prints 44.


Verification / Alternative check:
Create multiple objects and call Display(); all show 44 because they share one static x.


Why Other Options Are Wrong:
0 ignores the later assignment; “Garbage” would require an uninitialized read; compile-time error is inapplicable because out-of-class definition is provided.


Common Pitfalls:
Forgetting to define the static member outside the class; treating static members as per-object fields.


Final Answer:
The program prints 44.

More Questions from Objects and Classes

Discussion & Comments

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