Search code examples
c++visual-studio-2017lnk2001

Error LNK2001 in Visual Studio 2017 when using static int


I'm doing some practice tasks for uni and I'm supposed to create static int field inside a class, but when I do so I get error LNK2001. When I change it to regular int the error does not occure. Can anybody help me please? Here's my code:

#include <iostream>
#include <string>

using namespace std;

class Uczelnia {
public:
    virtual string getName() = 0;

    static int liczba_wszystkich_studentow;

};

class Politechnika:public Uczelnia {
public:
    Politechnika(string a, int b) {
        nazwa = a;
        liczba_studentow = b;
        liczba_wszystkich_studentow = +liczba_studentow;
    }

    string getName() {
        cout << "Politechnika: " << nazwa << endl;
        return nazwa;
    }

    ~Politechnika() {
        liczba_wszystkich_studentow = -liczba_studentow;
    }

private:
    string nazwa;
    int liczba_studentow;
};

class Uniwersytet :public Uczelnia {
public:
    Uniwersytet(string a, int b) {
        nazwa = a;
        liczba_studentow = b;
        liczba_wszystkich_studentow = +liczba_studentow;
    }

    string getName() {
        cout << "Uniwersytet: " << nazwa << endl;
        return nazwa;
    }

    ~Uniwersytet() {
        liczba_wszystkich_studentow = -liczba_studentow;
    }

private:
    string nazwa;
    int liczba_studentow;
};



int main() {
    Politechnika p1("Warszawska", 200);
    p1.getName();

    Uniwersytet u1("Warszawski", 600);
}

Solution

  • You're getting a linker error because you haven't initialized the static member. You just need to initialize it outside of the class.

    class Uczelnia {
    public:
    //..
        static int liczba_wszystkich_studentow;
    //..
    };
    
    int Uczelnia::liczba_wszystkich_studentow = 5;
    

    There are some additional intricacies of being able to initialize static const integral types (like int) inside of the class, but with others you would typically initialize these static members in the source file outside of the class definition.