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; }

C++ Programming Objects and Classes Difficulty: Easy
Choose an option
  • A
    The program will print the output 0.
  • B
    The program will print the output 33.
  • C
    The program will print the output Garbage.
  • D
    The program will report compile time error.
  • E
    The 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:

  • 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.

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