I want to have a simple class that I can call to get a unique number while the program is running. I can do the following with dynamic allocation, and then just deletewhen it is not needed, but I still wanted to get a static. Oddly enough, the code below (which would seem to be straightforward) causes some strange errors (attached below).
Any ideas what is going on? is it the wrong use of static?
class Id_gen {
private:
static int curr_id;
public:
Id_gen() {curr_id = 1; cout<<"debug:constructed"; }
int get_id() {curr_id++; return curr_id; };
};
int main () {
Id_gen bGen;
cout << bGen.get_id() <<endl;
return 0;
}
g ++ (linux 64) works:
c++2.cpp:(.text._ZN6Id_genC1Ev[Id_gen::Id_gen()]+0xe): undefined reference to `Id_gen::curr_id'
/tmp/cc766N6p.o: In function `Id_gen::get_id()':
c++2.cpp:(.text._ZN6Id_gen6get_idEv[Id_gen::get_id()]+0xa): undefined reference to `Id_gen::curr_id'
c++2.cpp:(.text._ZN6Id_gen6get_idEv[Id_gen::get_id()]+0x13): undefined reference to `Id_gen::curr_id'
c++2.cpp:(.text._ZN6Id_gen6get_idEv[Id_gen::get_id()]+0x19): undefined reference to `Id_gen::curr_id'
source
share