C++ mixing static and non-static access: does calling a non-static member via class name compile?\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 void Display()\n {\n cout<< x;\n }\n};\nint CuriousTab::x = 0;\nint main()\n{\n CuriousTab::SetData(33);\n CuriousTab::Display();\n return 0;\n}

Difficulty: Easy

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:

  • SetData is static and valid to call as CuriousTab::SetData(33).
  • Display is non-static.
  • main attempts CuriousTab::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.

More Questions from Objects and Classes

Discussion & Comments

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