General Class Question

The output for this code is myCount.count = 0, and times = 0 every iteration. I am trying to figure out why it's not 100 for both after the for loops final iteration.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;
class Count
{
  public:
  int count;

  Count(int c)
  {
  count = c;
  }

  Count()
  {
  count = 0;
  }
};

void increment(Count c, int times)
{
  c.count++;
  times++;
}

int main()
{
  Count myCount;
  int times = 0;
  for (int i = 0; i < 100; i++)
  {
    increment(myCount, times);
    cout << "myCount.count is " << myCount.count << endl;
    cout << " times is " << times << endl;
  }
  system("pause");
  return 0;
}
Last edited on
That's because you are passing a copy of the class when you put it into the function. If you want to modify it in the function, you'll have to pass it by reference (or pointer).

See: http://cplusplus.com/doc/tutorial/functions2/
The increment function is only modifying local copies of "c" and "times", which aren't reflected when you leave the function. You want to pass by reference.

That said, unless this is for a random academic purpose or something, this class is rather strange. It would work much better, I would think, if increment() were a method of Count.
Thanks a lot for both of your help.
Topic archived. No new replies allowed.