c++variablesscopeinitialization

Why doesn't it matter in which order define variables in class scope?


If we execute such two lines in any function, we will get an error, and this is logical because the variable b is defined after the initialization a=b:

int a=b;
int b=0;

But when we insert these two lines into the scope of a class, why doesn't the class care about in which order b is defined?

class Foo {
    int a=b;
    int b=0;
};

Solution

  • It does matter in which order you declare the members in a class.

    The order determines in which order they are initialized. Using the default initializers like in your example is roughly equivalent to using this constructor with member initializer list:

    class Foo
    {
        int a;
        int b;
        Foo() : a(b) , b(0) {}   // !! undefined !!
    };
    

    Here, still the order of initializion is determined by the order the members are declared, not by their order in the member initializer list. Compilers usually warn when the order is different. Though, in the above the problem gets more obvious: a is initialized with b before b is initialized. Reading from b before its initialization is undefined behavior.

    To correctly iniitalize one member with the value of another you must respect the order:

    class Foo
    {
        int b = 0;  // initialized first
        int a = b;  // OK
    };