Counter variable not storing

Trying to write a program that increases a int when called and saves the int so when called again its previous int+1. At the moment it returns all zeros.

Heres my code:
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//This is counter.h
#ifndef COUNTERHELP_H
#define COUNTERHELP_H


class counterhelp
{
    public:
    int getnextnumb () {
    for (int i=0; i<1000000; i++) {
        int counter = getcounter ();
        counter++;
        setcounter ();
    }
    return counter;
}
    int getcounter () {
        return this->counter;
}

    void setcounter () {
        this->counter = counter;
}
        counterhelp();
        virtual ~counterhelp();
    protected:
    private:
    int counter;
};

#endif
//This is counter.cpp
#include "C:\Documents and Settings\Jared\My Documents\CodeBlocks\Trial and Error\include\counterhelp.h"




counterhelp::counterhelp () {

}



counterhelp::~counterhelp()
{
    //dtor
}

//This is main.cpp
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include "C:\Documents and Settings\Jared\My Documents\CodeBlocks\Trial and Error\include\counterhelp.h"
using namespace std;

counterhelp ch;

int main () {
    int bob = ch.getnextnumb ();
    cout << " next number is " << bob;
    int susie =ch.getnextnumb ();
    cout << " next number is " << susie;
    int marc =ch.getnextnumb ();
    cout << " next number is " << marc;
}


See comments:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class counterhelp
{
    public:
    int getnextnumb () { //the entire function could be reduced to "return counter++;"
    for (int i=0; i<1000000; i++) { //what's up with the loop?
        int counter = getcounter ();
        counter++;
        setcounter (); //set counter to what?
    }
    return counter;
}
    int getcounter () {
        return this->counter; //just counter is sufficient
}

    void setcounter () { //this function needs a parameter to make any sense
        this->counter = counter; //assigns counter to itself, so that does nothing
}
        counterhelp();
        virtual ~counterhelp(); //no need for a virtual destructor as long as there are no other virtual functions
    protected:
    private:
    int counter;
};
Thank you, it worked.
Topic archived. No new replies allowed.