Static data members must be explicitly defined in exactly one source file. Here's an example of a header file, such as Fred.hpp. class Fred { public: static int x_; <-- 1 };
The linker generates an error ("Fred::x_ is not defined") unless (exactly) one of the source files defines Fred::x_. This definition is normally done in the class's source file, such as file Fred.cpp: #include "Fred.hpp" int Fred::x_ = 42; <-- 1
Note that the explicit initializer (= 42 in the example) is optional. That is, the line could be changed to int Fred::x_; <-- 1
Note that even when the static data member is private: or protected:, it must still be explicitly defined as shown in one of the two examples. |