I wanted to experiment with the code from the question on SO.
#include <iostream> using namespace std; class Base { public: static int staticVar; }; class DerivedA : public Base {}; class DerivedB : public Base {}; int main() { DerivedA::staticVar = 1; DerivedB::staticVar = 2; cout << DerivedA::staticVar << ' ' << DerivedB::staticVar << endl; return 0; } An error occurs
/home/ZzCHQ7/ccFrP214.o: In function `main ':
prog.cpp :(. text.startup + 0x13): undefined reference to `Base :: staticVar '
collect2: error: ld returned 1 exit status
As far as I understand, the compiler interprets static int staticVar; not as a variable creation, but as an external variable declaration
Tried to fix it like this :
class Base { public: static int staticVar; }; Base::staticVar(0); prog.cpp: 5: 16: error: expected constructor, destructor, or type conversion before '(' token
Base :: staticVar (0);
^
and so
class Base { public: static int staticVar; }; Base::staticVar = 0; prog.cpp: 5: 7: error: 'staticVar' in 'class Base' does not name a type
Base :: staticVar = 0;
^
How to write this construction correctly?