Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not set a value for static variable inside the class?

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;
    }

};
like image 714
Andrew Avatar asked Feb 23 '26 12:02

Andrew


1 Answers

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.

like image 112
Maxim Egorushkin Avatar answered Feb 25 '26 03:02

Maxim Egorushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!