Search code examples
c++classmemberautodecltype

Why does the order of the class members matter?


My compiler is GCC 4.9.0.

struct A {

    int n;

    auto f() -> decltype(n) { // OK
        return n;
    }
};

struct B {

    auto f() -> decltype(n) { // error: 'n' was not declared in this scope
        return n;
    }

    int n;
};

int main() {

    return A().f() + B().f();
}

Why does the order of the class members matter?


Solution

  • The declarations are compiled in order. It's the same reason you can't write:

    int y = x;
    int x = 5;
    

    The bodies of inline functions (incl. c-tor initiailizer lists) are processed later (parsed first of course, but the names aren't looked up until after the class definition is complete) so they can refer to class members that are on later lines.