using constants and statics to create ID's for object.

I am trying to create a unique ID for each object that is created within the program that I can refer to.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class character
{
public:

    character()
    {
        playerID = playerNum;
        playerNum++;
    }
... // Cut
private:
... // Cut
    static int playerNum;
    const int playerID;

The problem is that I get these errors when I try to compile it:

||=== Build: Debug in D&D CH (compiler: GNU GCC Compiler) ===|
main.cpp||In constructor 'character::character()':|
main.cpp|12|error: uninitialized member 'character::playerID' with 'const' type 'const int' [-fpermissive]|
main.cpp|14|error: assignment of read-only member 'character::playerID'|
main.cpp||In member function 'character& character::operator=(const character&)':|
main.cpp|8|error: non-static const member 'const int character::playerID', can't use default assignment operator|
main.cpp|In member function 'void encounter::combineALL()':|
main.cpp|179|note: synthesized method 'character& character::operator=(const character&)' first required here |
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|


How can I get playerNum to increment, and get written to playerID on creation of each new object?
Since playerID is const, you can't modify it inside functions like that. You have to initialize it in the constructor's initializer list:

1
2
3
character() : playerID(playerNum) {
    playerNum++;
}
Ok, I did that, and my errors reduced to this one
main.cpp|8|error: non-static const member 'const int character::playerID', can't use default assignment operator|

What is that supposed to mean?
Since your class has const data members, you can't use the default operator =. You will need to make your own (or tell the compiler that you don't want it to exist).
Topic archived. No new replies allowed.