C++ static counter across class functions: after First() then Second(5), what does Display() print?\n\n#include<iostream.h>\nclass CuriousTab\n{\n static int count;\n public:\n static void First(void)\n {\n count = 10;\n }\n static void Second(int x)\n {\n count = count + x;\n }\n static void Display(void)\n {\n cout<< count << endl;\n }\n};\nint CuriousTab::count = 0;\nint main()\n{\n CuriousTab::First();\n CuriousTab::Second(5);\n CuriousTab::Display();\n return 0;\n}

Difficulty: Easy

Correct Answer: 15

Explanation:


Introduction / Context:
This program demonstrates how a static data member preserves state across multiple static member function calls. Each method modifies the same single count variable owned by the class.


Given Data / Assumptions:

  • count is defined and zero-initialized outside the class.
  • First() assigns 10 to count.
  • Second(5) adds 5 to the existing value.
  • Display() prints the resulting value.


Concept / Approach:
Static data members are shared across all invocations and objects. Once count is set to 10, adding 5 yields 15, which is then printed.


Step-by-Step Solution:
1) After First(), count = 10. 2) After Second(5), count = 10 + 5 = 15. 3) Display() prints 15.


Verification / Alternative check:
Call Second(-5) instead, and you would see 5 printed, confirming state mutation.


Why Other Options Are Wrong:
0/5/10 reflect intermediate or initial states, not the final state after both calls. There is no compile-time error because the static member is defined.


Common Pitfalls:
Forgetting out-of-class definition; assuming each method works on a separate copy of count.


Final Answer:
15

More Questions from Objects and Classes

Discussion & Comments

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