In C++, class variables are initialized in the same order as they appear in the class declaration.
Consider the below code.
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.
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 DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Static data members in C++
- Can we access private data members of a class without using a member or a friend function?
- Memory Allocation in Static Data Members in C++
- Are array members deeply copied?
- Flexible Array Members in a structure in C
- Different ways to Initialize all members of an array to the same value in C
- C++ Program to swap two members using Friend Function
- Initialization of static variables in C
- Initialization of variables sized arrays in C
- Initialization of global and static variables in C
- Implicit initialization of variables with 0 or 1 in C
- Zero Initialization in C++
- Initialization of a multidimensional arrays in C/C++
- Uniform Initialization in C++
- Difference between fundamental data types and derived data types
- Data type of character constants in C and C++
- Data type of case labels of switch statement in C++?
- Structure Member Alignment, Padding and Data Packing
- How to print range of basic data types without any library function and constant in C?
- Data Type Ranges and their macros in C++