Has the new C++11 member initialization feature at declaration made initialization lists obsolete?

前端 未结 3 728
遥遥无期
遥遥无期 2020-11-29 18:11

With C++11, we now have the ability to initialize class members in a header declaration:

class aClass
{
    private:
        int mInt{100};
    public:
              


        
3条回答
  •  死守一世寂寞
    2020-11-29 18:42

    No, they are not obsolete.

    Initialization lists are still the only way to go if you need a constructor's arguments to initialize your class members.

    class A
    {
      int a=7; //fine, give a default value
    public:
      A();
    };
    
    class B
    {
      int b; 
    public:
      B(int arg) : b(arg) {}
    
      B(int arg, bool b) : b(arg) { ... }
    };
    

    Note that if both are present, the constructor's initialization will take effect, overriding the class member initialization, which is useful to specify a default value for a class member.

提交回复
热议问题