the order of the initializer list

Hello there,
I have read that the order of the initializer list in the ctor should follow the order in which the data members were declared, but i don't get any errors when i brake that rule ?
Is there something wrong with my compiler or what ?
It's not a rule, it's a recommendation. Regardless of which order you use in the constructor initializer list, the members are always initialized in the order they are declared. The recommendation is so that you don't get confused.
It can lead to problems:

1
2
3
4
5
6
7
8
9
10
11
12
13
class correct
{
    int y;
    int x;
    correct(int a) : y(a), x(y + 5) {}
};

class incorrect
{
    int x;
    int y;
    incorrect(int a) : y(a), x(y + 5) {}
}
First one works fine, but you will find that thewre is some garbage value in x member.
That is because it is actually evaluated as:
1
2
 x(y + 5) //y is uninitialized here
y(a) //too late 
Is there something wrong with my compiler or what ?

What compiler are you using? g++ can warn you of this issue, if you add the -Weffc++ switch.

I use g++ and i don't get any warnings.
Anyway thanks guys i got it, thank you MiiNiPaa you made a good point.
one quick thing: in the gcc documentation it says that library files don't always comply with the
-Weffc++ switch.
so you might get a heap of warnings.

Any way I guess that it is not too much of a brain strain to put them in order :+)
Topic archived. No new replies allowed.