C++ - initializing variables in header vs with constructor

前端 未结 7 908
盖世英雄少女心
盖世英雄少女心 2021-01-31 02:00

Regarding the following, are there any reasons to do one over the other or are they roughly equivalent?

class Something
{
    int m_a = 0;
};

v

7条回答
  •  别那么骄傲
    2021-01-31 02:22

    Even though it's supported, this type of initialization will create bugs that will be pretty hard to track down. It's the type of "aesthetic optimization" that you will regret a couple months down the road.

    See the example below:

    class_x_1.h:

    class X
    {
    private:
        int x = 10;
    public:
         int GetX();
    };
    

    class_x_2.h:

    class X
    {
    private:
        int x = 20;
    public:
        int GetX();
    };
    

    class_x.cpp:

    #include "class_x_1.h" // implementation uses the version that initializes x with 10
    
    int X::GetX()
    {
        return x;
    }
    

    main.cpp:

    #include "class_x_2.h" // main includes definition that initializes x with 20
    
    #include 
    
    int main()
    {
        X x;
        std::cout << x.GetX() << std::endl;
        return 0;
    }
    

    Output:

    20
    

    As expected, it will return 20 because this is the version that initializes x with 20. However, if you go to the implementation of X, you might expected it to be 10.

提交回复
热议问题