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:
constshort ID = ++Foo::nextID;
private:
staticshort 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'".
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.
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.