Related Articles

Related Articles

Initialization of data members
  • Difficulty Level : Medium
  • Last Updated : 09 Jun, 2017

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

Consider the below code.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
  
using namespace std;
  
class Test {
  private:    
    int y;
    int x;    
  public:
    Test() : x(10), y(x + 10) {}
    void print();
};
  
void Test::print()
   cout<<"x = "<<x<<" y = "<<y; 
}
  
int main()
{
    Test t;
    t.print();
    getchar();
    return 0;    
}

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// First: Change the order of declaration.
class Test {
  private:    
    int x;    
    int y;
  public:
    Test() : x(10), y(x + 10) {}
    void print();
};

chevron_right


filter_none

edit
close

play_arrow

link
brightness_4
code

// Second: Change the order of initialization.
class Test {
  private:    
    int y;
    int x;    
  public:
    Test() : x(y-10), y(20) {}
    void print();
};

chevron_right


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

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :