C++ static data and static member functions: after setting x via a class-qualified call, what is printed?
#include
class CuriousTab
{
static int x;
public:
static void SetData(int xx)
{
x = xx;
}
static void Display()
{
cout<< x;
}
};
int CuriousTab::x = 0;
int main()
{
CuriousTab::SetData(44);
CuriousTab::Display();
return 0;
}
-
AThe program will print the output 0.
-
BThe program will print the output 44.
-
CThe program will print the output Garbage.
-
DThe program will report compile time error.
-
EThe program will print nothing.
Answer
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::xis defined and initialized to 0 outside the class.SetData(44)stores 44 into the staticx.Display()prints the current value ofx.
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.