I want to have a simple class i can call to get a unique number whilst the program is running - i can do the below with a dynamic allocation, and then just delete
when not needed, but i still wanted to get a static
version too.
Strangely, the code below (which is seemingly straightforward) throws some strange comiple errors (appended below).
Any ideas whats going on ? is this an incorrect use of static ?
class Id_gen {
private:
//adding static here stops the code from compiling:
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;
}
running g++ (linux 64):
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'