Initialization of data members

 

  In C++, class variables are initialized in the same order as they appear in the class declaration.

  Consider the below code.

 1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 class Test 
 6 {
 7 private:    
 8     int y;
 9     int x;    
10 public:
11     Test() : x(10), y(x + 10) 
12     {
13     }
14     void print();
15 };
16 
17 void Test::print()
18 { 
19     cout<<"x = "<<x<<" y = "<<y; 
20 }
21 
22 int main()
23 {
24     Test t;
25     t.print();
26     getchar();
27     return 0;    
28 }

 

  The program prints correct value of x, but some garbage value for y, because y is initialized before x as it appears before in the class declaration.

  So one of the following two versions can be used to avoid the problem in above code.

 1 // First: Change the order of declaration.
 2 class Test 
 3 {
 4 private:    
 5     int x;    
 6     int y;
 7 public:
 8     Test() : x(10), y(x + 10) 
 9     {
10     }
11     void print();
12 };
13 
14 // Second: Change the order of initialization.
15 class Test 
16 {
17 private:    
18     int y;
19     int x;    
20 public:
21     Test() : x(y-10), y(20) 
22     {
23     }
24     void print();
25 };

 

 

 

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-26  10:23:29

posted @ 2013-11-26 10:24  虔诚的学习者  阅读(146)  评论(0编辑  收藏  举报