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

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