1

I am Having trouble generating a unique id for each of my objects.

My objects are a song object witch has variables artist, genre etc.

so in my song.h file under private I have

private:
   int m_ID;
   static unsigned int IDSeed;

in my song.cpp file I have

Song::Song()
{
    static unsigned int IDSeed = 0;
    m_ID = IDSeed++;

}

Song::Song(constructor variables)
{

    m_ID = IDSeed++;

}

The main error I am getting now is "unresolved external symbol private static unsigned int Song::IDSeed"

Michael Grinnell
  • 922
  • 1
  • 12
  • 32
  • If you construct them all with the default constructor (`Song a; Song b; Song c;`), then you're setting all the IDs to zero. – Daniel H Oct 22 '17 at 18:24
  • _so in my song.h file under private I have_ Why you don't just show your song class declaration? Second, `static unsigned int IDSeed;` is different from `unsigned int IDSeed = 0;` – Amadeus Oct 22 '17 at 18:25
  • 1
    Can't you simply use the memory address of the object (`reinterpret_cast(this)`) as the unique ID? No two objects alive will share an address (although an object may be re-using the address of a past, now dead, one). – Jesper Juhl Oct 22 '17 at 18:44

3 Answers3

1

As it seems to me that IDSeed must be the same across Song objects, then, it must be declared static. So, in your song.h file, you must have something like that:

class Song {
    int m_ID;
    static unsigned int IDSeed;
    static int helper_seed() { IDSeed++; return IDSeed;}
    (...)
};

Now, you need to initialize your static member. So, in song.cpp:

unsigned int Song::IDSeed = 0;

Now, on each constructor of Song object, you can do something like this:

Song::Song()
{
    m_ID = helper_seed();    
}

Song::Song(constructor variables)
{
    m_ID = helper_seed();
}
Amadeus
  • 10,199
  • 3
  • 25
  • 31
1

You can use the memory address of the object - reinterpret_cast<std::uintptr_t>(this) - as the unique ID, as long as the ID just has to be unique amongst all currently alive objects.

No two objects alive will share an address (although an object may be re-using the address of a past, now dead, one).

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
0

In your code, static unsigned int IDSeed; does nothing. unsigned int IDSeed = 0; is a "usuall" class (instance) variable and it will be set to zero everytime you init your class. If you want to have persistent value, you must have this variable static. Also, you can remove static unsigned int IDSeed; from Song()

Martin Perry
  • 9,232
  • 8
  • 46
  • 114
  • Ok when i do that i get the error "a member with an in-class initializer must be const" If I place const in front of static unsigned int I get the error "++ needs na I_Value" – Michael Grinnell Oct 22 '17 at 18:35