Automatic ID for class objects

I want to have each object of some class have an ID, but I don't want to have to pass in an ID to the constructor whenever I make the object for it. I want to do something like this:

1
2
3
4
5
6
7
8
class Foo
{
public:
   const short ID = ++Foo::nextID; 

private:
   static short nextID;
}


But I get a compiler error for initializing ID like that. How would I do this? Would I have to do something in the constructor? Thanks in advance.

EDIT: The errors are "incomplete type 'Foo' used in nested name specifier", "'++' cannot appear in a constant-expression", "making 'ID' static", and "ISO C++ forbids initialization of member 'ID'".
Last edited on
closed account (zb0S216C)
For constant data members, you must use the constructor initializer list to initialize them (it). For example:

1
2
3
Foo::Foo( ) : ID( 0 )
{
}

The code following the colon is the initializer list. The list initializes the data members within it before they are used by the class. Note that the order of the items within the list must appear in the same order in which they are declared. Static members don't have a *this pointer so they cannot appear within the list.

Wazzak
Last edited on
Thanks for the fast reply. That works, but now I get an error that reads "undefined reference to 'Foo::nextID'". I did this:

1
2
Foo::Foo()
: ID(Foo::nextID)


I think it might be because I didn't initialize nextID, but I don't know how. I get an "ISO forbids" error when I try initializing it in the header.
closed account (zb0S216C)
Members that are declared static must be defined outside the class in which it's defined. This can be done, like such: short Foo::nextID( 0 ); .

Like I said, static members aren't associated with any instantiation of Foo, which means they cannot appear within an initializer list since initializer lists are associated with the constructor of the current instance. static members are shared between all instances.

Wazzak
Last edited on
Thanks for the help, it works now.
Topic archived. No new replies allowed.