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.
#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
filter_none
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.
// 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
// Second: Change the order of initialization. class Test { private: int y; int x; public: Test() : x(y-10), y(20) {} void print(); }; |
chevron_right
filter_none
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Static data members in C++
- Can we access private data members of a class without using a member or a friend function?
- Zero Initialization in C++
- Uniform Initialization in C++
- Different ways to Initialize all members of an array to the same value in C
- Are array members deeply copied?
- Flexible Array Members in a structure in C
- Initialization of static variables in C
- Implicit initialization of variables with 0 or 1 in C
- Initialization of a multidimensional arrays in C/C++
- C++ Program to swap two members using Friend Function
- Initialization of global and static variables in C
- Initialization of variables sized arrays in C
- Difference between fundamental data types and derived data types
- Data Types in C



