c++ data members initialization order when using initialization list

我的未来我决定 提交于 2020-01-14 13:04:31

问题


class A
{
private:
int a; 
int b; 
int c;

public:
A() : b(2), a(1), c (3)
{
}
};

As per C++ standard data members are constructed and initialized in the order they are declared, correct?

But when using initalization list, we are changing the order of data members, now do they initialize in order of initialization list or the order of declaration?


回答1:


In the order of declaration, the order in the initialization list does not matter. Some compilers will actually give you warning (gcc) telling you that the initialization list order is different than the order of declaration. This is why you also have to be careful when you would use members to initialize other members, etc.




回答2:


No, the initialization list has nothing to do with it.

Members are always initialized in the order in which they appear in the class body.

Some compilers will even warn you if the orders are different.




回答3:


They initialize in order of declaration. Also lot of compilers warn you that your initialization list does not match with declaration order, despite standard allows it.




回答4:


In C++11 you can also do:

class A
{
    private:
    int a = 1; 
    int b = 2; 
    int c = 3; 

public:
    A()
    {
       // your code
    }
};



回答5:


class data members are always initialized in top->bottom order of their declaration inside class and destructed in reverse order. Initialization list doesn't affects the order of initialization of data members.

You can check below related question as well for more tricky situations while using initialization lists,

How function call is working on an unitialized data member object in constructor's initilalizer list



来源:https://stackoverflow.com/questions/12126209/c-data-members-initialization-order-when-using-initialization-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!