tags:

views:

88

answers:

5

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'
+2  A: 

You need to define the static variable outside the class as:

int Id_gen::curr_id;
codaddict
A: 

You have to define the static member in a translation unit (cpp file):

int Id_Gen::curr_id = 0; // Initial value
Cătălin Pitiș
A: 

You must define the static instance variable in your class implementation, i.e.:

int Id_Gen::curr_id = 0;
swegi
+3  A: 

Add the initialization/definition of the static member as:

int Id_gen::curr_id = 0;

after the class definition.

EDIT: As mentioned in the comment by @sbi : Initialization is optional, the linker requires the definition only.

Akanksh
Initialization isn't important for the linker. It's the __definition__ the linker needs.
sbi
A: 

As mentioned by others you need to define the variable outside of the class:

int Id_Gen::curr_id;

If there is nothing else in this class you could omit the constructor and initialise this variable when you define it and make the get_id() function static too. This would allow you to call Id_Gen::get_id() without creating an instance of the class. In its current state if you mistakenly created two Id_Gen's you would reset your id.

identitycrisisuk