I wanted to experiment with the code from the question on SO.

http://ideone.com/CIYA8i

#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?

    1 answer 1

    Like this:

     class Base { public: static int staticVar; }; int Base::staticVar = 3; 

    As far as I understand, the compiler interprets static int staticVar; not as a creation of a variable, but as a declaration of an external variable.

    This is a declaration (declaration) of an object, and we still need its definition (definition). If this requirement did not exist (that is, the declaration would be a definition immediately), then in each module (cpp, in which the header is included) a new static variable would be defined, and this would be an ODR violation. Therefore, static class objects need to be defined outside the class, in the cpp file.

    • @Qwertiy, what's past? Compare your code and mine. Find the differences. Assign just like any other place. - ixSci
    • Oops .. Type forgot. ideone.com/Wh2oYi - yes, it works. Thank! - Qwertiy