I am new to c++ and experimenting with classes and static variables.
I have found the solution to making the code run but I am not sure why this works and why my previous method did not
#include <iostream>
using namespace std;
class Person {
static int id;
public:
void createPerson() {
id++;
cout << id << endl;
}
};
int Person::id = 0;
int main() {
Person Person1;
Person Person2;
Person1.createPerson();
Person2.createPerson();
}
I am wondering why I must declare the value of id outside the class. And why I cannot have something like..
class Person {
static int id = 0;
public:
void createPerson() {
id++;
cout << id << endl;
}
};
static data members are not parts of objects, so you need to tell the compiler explicitly in which translation unit to store them by providing that definition.
Note that static data members of class templates can be defined in the header files.
In C++17 a static data member can be declared as inline, so that no out-of-line definition is necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With