Same initialization as declaration in constructor, why?

I was looking through the basic tutorial on C++ with an FRC robot.

The code:


The comments say these declarations have to be initialized in the same order as they are declared.

Why is this?

I don’t know of anything in the C++ standard that requires the member initialization list to be in declaration order. It might be some limitation of the compiler, or they might be encouraging that for code readability because the C++ standard does say that no matter the order in the initialization list, the class members will be initialized in the order they are declared in the class definition.

I don’t have windriver installed so I can’t check to be sure which it might be, but there’s nothing keeping you from trying it out. What happens if you reverse the initializers in the example code and try to compile it?

Its not a requirement, but strongly recommended, as giving them a different order will lead to very unintuitive behavior, as well as a warning from GCC. As Ryan said, no matter what you put in the initialization list, the members’ll be initialized in the order they are declared up above.

The reason for this is that if you want to declare a member variable as some transformation of another member variable, you can end up with declaring it before the first variable is initialized. So, if you have:

class Example {
    int a;
    int b;

    b(2), a(b+1) {

the value of a will not be 3, but undefined, even though it looks like it’s declared after b. It’s not a compiler error to have them in a different order, but it will produce a warning (I believe the warning is “warning: when initialized here”).