C++ Initialising fields directly vs initialisation list in default constructor

前端 未结 3 1341
执笔经年
执笔经年 2021-01-03 20:16

I\'d like to know if there is a difference between this code:

class Foo{
 private:
    int a = 0;
 public:
    Foo(){}
}

And:



        
3条回答
  •  有刺的猬
    2021-01-03 21:08

    From cppreference - Non-static data members

    Member initialization
    1) In the member initializer list of the constructor.
    2) Through a default member initializer, which is simply a brace or equals initializer included in the member declaration, which is used if the member is omitted in the member initializer list.

    If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored.


    To conclude, both initializers are equivalent and do what they are supposed to do.

    I would prefer the default member initializer, if I'd use the default constructor anyway, or if all or most constructors would initialize the member to the same value.

    class Foo {
    private:
        int a = 0;
    };
    

    If all constructors initialize the member to some different value however, using the default member initializer makes less sense, and then an explicit initialization in the respective constructors would be more clear

    class Foo {
    private:
        int a;
    public:
        Foo() : a(3) {}
        Foo(int i) : a(i) {}
    };
    

提交回复
热议问题