I’m trying to make a “Person” class with a static member variable id_index to keep track of the ID for the next class created(so no two classes have the same ID). When I run the program I get these errors:
G:\WorkSpace\Human\Debug/../Person_Class/Person.cpp:11: multiple definition of `Person::id_index'
Person_Class\Person_Set.o:G:\WorkSpace\Human\Debug/../Person_Class/Person_Set.cpp:10: first defined here
Human.o: In function `main':
G:\WorkSpace\Human\Debug/../Human.cpp:16: multiple definition of `Person::id_index'
Person_Class\Person_Set.o:G:\WorkSpace\Human\Debug/../Person_Class/Person_Set.cpp:10: first defined here
This is the person.h file:
#ifndef PERSON_H_
#define PERSON_H_
#include <iostream>
class Person {
public:
static unsigned int id_index; // will aut0-set to 0
Person();
};
unsigned int Person::id_index = 0;
#endif /* PERSON_H_ */
The person.cpp:
Person::Person(): ID(id_index) {
}
Main function stored inside human.cpp:
int main(){
Person michael;
return 0;
}
The second to last line of your person.h file, the
unsigned int Person::id_index = 0;belongs in the person.cpp.Similarly to how function definitions belong in the .cpp, static variable definitions(which is what that line is) also belong in the .cpp.