what is the advantage of using a static int in class

Nov 6, 2012 at 4:15pm
i was in the process of experimenting with it when my compiler stopped working, if i could get the answer i can be satisfied i have learnt enough for todai
Nov 6, 2012 at 4:18pm
what's the relation between static int and your problem? maybe it is somewhere in your code, can you show us your full code?
Nov 6, 2012 at 4:18pm
none at all, i was trying to study static ints and i have a seperate prblem, i was just curious as how to use them, theres no code cos my compiler wont even reconize int for sum reason :(
Last edited on Nov 6, 2012 at 4:19pm
Nov 6, 2012 at 4:20pm
will just go ahh and then i can fix my compiler tommorow without being bugged by not knowing something, its workin

kay here this code provees i dont get it

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
using namespace std;

class bunny{
    public:
static int x;
void upint ()
{
    x++;
}
void getint ()
{
    cout << x;
}
};

int main()
{
    bunny bugs;
    bunny baxter;

bugs.upint();
bugs.getint();
    return 0;
}
Last edited on Nov 6, 2012 at 4:52pm
Nov 6, 2012 at 5:15pm
kay here this code provees i dont get it


When posting something like this it is generally useful to include germane information such as why you believe it proves you don't get it or what difficulties you have compiling or linking the code.

In the snippet you provided you declare x, but never define it.

A member function named "getint" should probably return an int and not insert stuff into an output stream.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <vector>
#include <iostream>
using namespace std;

class bunny{
    static unsigned n_bunnies ;
public:

    bunny() { ++n_bunnies; }
    bunny(const bunny& b) { ++n_bunnies; }
    ~bunny() {--n_bunnies ;}

    static unsigned bunny_count() { return n_bunnies ; }
};

unsigned bunny::n_bunnies = 0 ;

int main()
{
    vector<bunny> bunnies(12) ;
    cout << bunny::bunny_count() << '\n' ;
}


Notice the definition of the static member on line 16.
Last edited on Nov 6, 2012 at 5:16pm
Nov 6, 2012 at 6:41pm
The advantage of static int in a class is there will only be one instance of the int regardless of the number of class objects created.
Nov 7, 2012 at 12:07am
thanks guys i really didnt know how to go about understanding the tutorials
Topic archived. No new replies allowed.