0

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);
}
  • Do you have any code file doing the actual definition of `static int liczba_wszystkich_studentow;`? What you show is only the declaration inside the class. You need something like `static int Uczelnia ::liczba_wszystkich_studentow=0;` in a code file. – Yunnosch Jan 14 '20 at 19:29

2 Answers2

1

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.

Chris
  • 2,254
  • 8
  • 22
0

Within a class definition there are declarations of static data members not their definitions. Declared static data members within a class definition may even have an incomplete type. If a static data member is ODR used it shall be defined outside a class definition in some module. For example

int Uczelnia::liczba_wszystkich_studentow;

In C++ 17 you can use the inline specifier in a declaration of a static data member within a class definition.

For example

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

    inline static int liczba_wszystkich_studentow;

};

In this case the code will compile provided that the compiler supports C++ 17..

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335