FAQ 22.05 How is a const data member initialized?

FAQ 22.05 How is a const data member initialized?

Nonstatic const data members are declared in the class body with a const prefix, and their state must be initialized in the constructor's initialization list. The value used to initialize the const data member can be a literal value, a parameter passed to the constructor, or the result of some expression. After initialization, the state of a const data member within a particular object cannot change, but each object can initialize its const data member to a different value.

In the following example, i_ is a non-const member variable and j_ is a const member variable.

 class Fred { public:   Fred(int i)        throw();   Fred(int i, int j) throw(); protected:   int i_;   const int j_; }; Fred::Fred(int i) throw() : i_(i) , j_(10)                                             <-- 1 { } Fred::Fred(int i, int j) throw() : i_(i) , j_(j)                                              <-- 2 { } int main() {   Fred a(5);      //a.j_ will always be 10   Fred b(5,15);   //b.j_ will always be 15   Fred c(5,20);   //c.j_ will always be 20 } 

(1) Initialize const member j_ with a literal value

(2) Initialize const member j_ with a constructor parameter



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