C++ mixing static and non-static access: does calling a non-static member via class name compile?
#include
class CuriousTab
{
static int x;
public:
static void SetData(int xx)
{
x = xx;
}
void Display()
{
cout<< x;
}
};
int CuriousTab::x = 0;
int main()
{
CuriousTab::SetData(33);
CuriousTab::Display();
return 0;
}
-
AThe program will print the output 0.
-
BThe program will print the output 33.
-
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 report compile time error.
Explanation
Introduction / Context:
Here we test whether a non-static member function can be called using the class name alone. While static members can be invoked with the class scope operator, non-static members require an object to supply the hidden this pointer.
Given Data / Assumptions:
SetDatais static and valid to call asCuriousTab::SetData(33).Displayis non-static.mainattemptsCuriousTab::Display()with no object.
Concept / Approach: Non-static functions depend on an instance. Calling Display() without an object is ill-formed because there is no this to operate on.
Step-by-Step Solution: 1) The class defines a static data member and both static and non-static methods. 2) The statement CuriousTab::Display() tries to bind a non-static method to no instance. 3) The compiler emits an error indicating that a non-static member function requires an object.
Verification / Alternative check: If you instead created CuriousTab obj; and called obj.Display();, it would compile and print 33.
Why Other Options Are Wrong: Any printed output presumes successful compilation, which is not the case here.
Common Pitfalls: Confusing when class scope access is allowed; forgetting the difference between static and instance members.
Final Answer: Compile-time error.