C++ - initializing variables in header vs with constructor

前端 未结 7 911
盖世英雄少女心
盖世英雄少女心 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:30

    Elaborating on Christian Hackl's answer.

    The first form allows to initialize m_a and have a default c'tor at the same time. Or you can even be explicit in your code and define a constructor with the default keyword:

    class Something
    {       
        int m_a = 0;
    
        // explicitly tell the compiler to generate a default c'tor
        Something() = default;
    };
    

    With the second form, an auto-generated default c'tor would leave m_a uninitialized, so if you want to initialize to a hard-coded value, you have to write your own default c'tor:

    class Something
    {
        int m_a;
    
        // implement your own default c'tor
        Something() : m_a(0) {}
    };
    

提交回复
热议问题