Consider the following (simplified) situation:
class Foo
{
private:
int evenA;
int evenB;
int evenSum;
public:
Foo(int a, int b) : evenA(a-(a%2)), evenB(b-(b%2)), evenSum(evenA+evenB)
{
}
};
When i instanciate Foo like this:
Foo foo(1,3);
then evenA is 0, evenB is 2, but will evenSum be initialized to 2?
I tried this on my current platform (iOS) and it seems to work, but I'm not sure whether this code is portable.
Thanks for your help!
Members are initialized in the order they're declared in the class definition. As long as your initializer list follows this order, it should be ok.
This is well-defined and portable,1 but it's potentially error-prone.
Members are initialized in the order they're declared in the class body, not the order they're listed in the initialization list. So if you change the class body, this code may silently fail (although many compilers will spot this and emit a warning).
1. From [class.base.init] in the C++ standard(s):
(Highlighting is mine.)
This section of the standard then goes on to give an example of using member variables to initialize other member variables.
This also compiled without error on g++ 4.0.3 (6 years old now).
I feel confident this will compile fine on any reasonably recent compiler.
Yes, provide they've already been constructed. Just don't forget that the order of construction is the order of the declarations in the class definition, not the order of the initializers in the constructor. And that the compiler typically won't tell you if you use a variable before it has been constructed. In your case, for example, if you move
evenSum
to the top of the class, you have undefined behavior (because its initializer uses uninitialized members), even though in your constructor, you initializeevenA
andevenB
lexically beforeevenSum
.