简体   繁体   中英

C++ multiple access specifiers and order of initialization

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM