C++ static member functions: does using this-> inside a static method compile? Examine and predict the program's behavior.
#include
class CuriousTab
{
static int x;
public:
static void SetData(int xx)
{
this->x = xx; // attempt to use this in a static function
}
static void Display()
{
cout << x;
}
};
int CuriousTab::x = 0;
int main()
{
CuriousTab::SetData(22);
CuriousTab::Display();
return 0;
}
-
AThe program will print the output 0.
-
BThe program will print the output 22.
-
CThe program will print the output Garbage.
-
DThe program will report compile time error.
-
EIt links but crashes at run time.
Answer
Correct Answer: The program will report compile time error.
Explanation
Introduction / Context:This question checks your understanding of C++ static member functions and the absence of the implicit this pointer inside them. It asks whether referencing this->x in a static method is legal.
Given Data / Assumptions:
xis a static data member.SetDataandDisplayare static.SetDataincorrectly usesthis->x.
Concept / Approach:A static member function is not associated with any particular object instance, so it has no this pointer. Any attempt to use this inside a static member function is ill-formed and rejected by the compiler.
Step-by-Step Solution:Note the signature static void SetData indicates no object context.Inside it, this is referenced, which is invalid.The compiler issues an error; execution never occurs.
Verification / Alternative check:Replace this->x with CuriousTab::x (qualified name) or simply x and the code will compile and print 22.
Why Other Options Are Wrong:They assume successful compilation or run-time behavior. The error arises at compile time.
Common Pitfalls:Confusing static context with instance context and trying to use this where it does not exist.
Final Answer:The program will report compile time error.