CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List
C++ Code Walkthrough #79

Two Files: Declaration in the Header, Definition in the .cpp

mediumModular Programming

📄 Code

Read carefully — what does this print?
1// ===== Counter.h =====
2#ifndef COUNTER_H
3#define COUNTER_H
4 
5class Counter {
6 int m_value;
7 static int s_created;
8public:
9 Counter();
10 Counter(int start);
11 void bump();
12 int value() const;
13 static int created();
14};
15 
16#endif
17 
18// ===== Counter.cpp =====
19#include "Counter.h"
20 
21int Counter::s_created = 0;
22 
23Counter::Counter() : m_value(0) {
24 s_created++;
25}
26 
27Counter::Counter(int start) : m_value(start) {
28 s_created++;
29}
30 
31void Counter::bump() {
32 m_value += 2;
33}
34 
35int Counter::value() const {
36 return m_value;
37}
38 
39int Counter::created() {
40 return s_created;
41}
42 
43// ===== main.cpp =====
44#include <iostream>
45#include "Counter.h"
46using namespace std;
47 
48int main() {
49 Counter a;
50 Counter b(10);
51 a.bump();
52 b.bump();
53 b.bump();
54 Counter c = b;
55 cout << a.value() << " " << b.value() << " " << c.value() << endl;
56 cout << Counter::created() << endl;
57 return 0;
58}

🎯 Your Answer