FAQ 16.10 Why might a class with static data members get linker errors?

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 }; 

(1) Declare (not define) static member Fred::x_

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 

(1) Define static member Fred::x_

Note that the explicit initializer (= 42 in the example) is optional. That is, the line could be changed to

 int Fred::x_;                                        <-- 1 

(1) Initialize Fred::x_ to 0

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.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net