What's the differences between member initializer list and default member initializer on non-static data member?

前端 未结 5 784
醉话见心
醉话见心 2020-12-28 18:13

I\'d like to understand what\'s the differences of using one form rather than the other (if any).

Code 1 (init directly on variables):

#include 

        
5条回答
  •  渐次进展
    2020-12-28 18:56

    There is no difference in the code. The difference would come if you would be would have more than one constructor overload and in more than one count would be 10. With the first version you would have less writing to do.

    class Test 
    {
    public:
        Test() = default;
        Test(int b) : b(b) {} // a = 1, c = 3
    
        ~Test();
    
    private:
        int a = 1;
        int b = 2;
        int c = 3;
    };
    

    As opposed to the second version where the above code would look like this:

    class Test 
    {
    public:
        Test() : a(1), b(2), c(3) {}
        Test(int b) : a(1), b(b), c(3) {}
    
        ~Test();
    
    private:
        int a;
        int b;
        int c;
    };
    

    The difference gets bigger with more member variables.

提交回复
热议问题