class A
{
private:
int x;
int y;
int z;
public:
A(int val) : x(++val), z(++val), y(++val)
{
std::cout << "y--->" << y<< std::endl;
}
};
int main()
{
A a(3);
return 0;
}
Asked
Active
Viewed 194 times
0

Cory Kramer
- 114,268
- 16
- 167
- 218

Navneet
- 1
-
Use code formatting and describe your problem in details please – Ladence Jan 14 '20 at 12:48
-
4From the standard *nonstatic data members shall be initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers)*. Some code analyzers and compilers will emit warnings for the member initializer list not matching the order of the members in the class for this exact reason. – Cory Kramer Jan 14 '20 at 12:50
-
2A decent compiler should (with the right options enabled) [give a warning about the initialization order](https://godbolt.org/z/8H2ypa). Always make it a habit to enable almost all the warnings possible. – Some programmer dude Jan 14 '20 at 12:50
-
In above question i am initializing the x, y and z . after initializing the variable i getting the value of Y in 5 , since i have initialize it last, i was expecting value 6 . – Navneet Jan 14 '20 at 12:54
-
@Someprogrammerdude, I don't think VS does, but I did find a feature request for it [here](https://developercommunity.visualstudio.com/idea/854649/warn-about-member-variable-initialization-order.html) – ChrisMM Jan 14 '20 at 12:54
-
@ChrisMM I said *decent* compiler... ;) – Some programmer dude Jan 14 '20 at 12:56
-
1@Someprogrammerdude From `MSVC` (2019) with (almost) all warnings enabled: **warning C5038: data member 'A::z' will be initialized after data member 'A::y'** – Adrian Mole Jan 14 '20 at 12:59
-
So during construction initialization , precedence is not follow. – Navneet Jan 14 '20 at 13:00
-
2@Navneet `x(++val), z(++val), y(++val)` is not an expression, there is no notion of precedence there. Even if there was, precedence does not determine order of evaluation. And all that aside, initialization of class members happens in the order in which they are declared, not the order in the initializer list, as explained in the linked duplicate. – walnut Jan 14 '20 at 13:06
-
_"since i have initialize[d] it last"_ Nope, you haven't; you only think you have ;) – Lightness Races in Orbit Jan 14 '20 at 14:16
-
Since `val` is only used to initialize those three values, the way to write those initializers is `x(val+1), y(val+3), z(val+2)` (assuming the intention was to do the three increments in left-to-right order). You can put those in any order you like, and the initialization will be the same. – Pete Becker Jan 14 '20 at 15:26
-
Thank you guys for helping me to understand this . – Navneet Jan 16 '20 at 16:52