FAQ 16.11 How is a const static data member initialized?A const static data member is declared in the class and is normally defined (and initialized) in a source file, such as a .cpp file. But in some cases it can be initialized in the class body proper. For example, integral types, such as int, unsigned long, char, and so on, are special: they can be initialized where they are declared in the class body proper. Here is a sample header file, Fred.hpp. #include <string> using namespace std; class Barney { }; class Fred { public: // ... private: static const int i_ = 42; <-- 1 static const char c_ = 'z'; <-- 1 static const float x_; <-- 2 static const string s_; <-- 2 static const Barney b_; <-- 2 };
Here is corresponding source file, Fred.cpp. #include "Fred.hpp" const float Fred::x_ = 3.14; const string Fred::s_ = "Hello"; const Barney Fred::b_; Another common style is to use anonymous (unnamed) enums. This style is no longer needed, but it is typical in older C++ code. For example, the static const int i_ = 42 from the previous example can be replaced by enum { i_ = 42 }, as shown in the following example. class Fred { public: // ... private: enum { i_ = 42 }; <-- 1 // static const int i_ = 42; <-- 2 };
In either case, the constant is called Fred::i_, and it can be private:, protected:, or public:. |