1

I want to have a simple class that represents an object with unique id. Every new object gets an ID higher than the previously created one. Important thing to notice is that id for every object is constant, so I'm obliged to use initialise list. For some reason I get an error about undefined reference: Undefined reference to Test::ID.

class Test
{
    const int m_id;
    static int ID;
public:
    Test() : m_id(ID++)
    {
        cout << "Created object with id: " << m_id << endl;
    }
};
  1. Why is this?
  2. How can I fix this?
  3. How can I make sure that ID is pre-initialised with 0, so i don't increment an uninitialised variable?
  • It is not good idea to use variables in all uppercase – Slava Nov 17 '15 at 19:58
  • Hey, thanks for the advice... But why? Is it because of the common way of naming consts using uppercase only or there is some other reason behind this? – This is temp display name Nov 17 '15 at 20:13
  • 1
    Naming consts using uppercase is antipattern as well that comes from creating constants using preprocessor. Name collision with preprocessor are hard to catch and difficult to maintain, so either creating C++ constants and variables in uppercase is not a good idea. – Slava Nov 17 '15 at 20:22

1 Answers1

2

You need to reserve storage for the static in one translation unit. You initialise it then. So you need to write

int Test::ID = 0;

in one of your source files.

Consider changing the type to std::atomic<int>. Doing that will improve the thread safety of your code.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483