FAQ 16.11 How is a const static data member initialized?

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

(1) Integral data types can be initialized in the class body proper

(2) Nonintegral data types must be defined in the source file, not in the class body proper

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

(1) Older style

(2) Newer style

In either case, the constant is called Fred::i_, and it can be private:, protected:, or public:.



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