C++ multiple access specifiers and order of initialization

317 views Asked by At

We know that in the following code

class Foo1 {
private:
    int i;
    bool b;
public:
    Foo1() : i(7), b(false) {} 
};

"i" is going to be init before "b". If I try to init "b" before "i", I'll get a warning.

what about this case:

class Foo2 {
private:
    int i;
private:
    bool b;
public:
    // what happens if b is first because compiler reordered?
    Foo2() : b(false),  i(7) {} 
};

?

We know that the compiler is free to order "i" and "b" since they are in separate access specifiers.

So what is the order of initialization in this case?

anything guaranteed like in the previous simple case?

1

There are 1 answers

0
leslie.yao On BEST ANSWER

The order of initialization is guaranteed; i is always initialized before b. Non-static data members are initialized in the order of their declaration in the class definition, regardless of their access specifiers.

[class.base.init]/13.3

Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).