12.7 Non-static member initialization


https://www.learncpp.com/cpp-tutorial/non-static-member-initialization/
非静的member initを用いることができます
#include <iostream>

class Rectangle
{
private:
    double m_length{ 1.0 };
    double m_width{ 1.0 };

public:

    Rectangle(double length, double width)
        : m_length{ length },
          m_width{ width }
    {
        // m_length and m_width are initialized by the constructor (the default values aren't used)
    }

    Rectangle(double length)
        : m_length{ length }
    {
        // m_length is initialized by the constructor.
        // m_width's default value (1.0) is used.
    }

    void print()
    {
        std::cout << "length: " << m_length << ", width: " << m_width << '\n';
    }

};

int main()
{
    Rectangle x{ 2.0, 3.0 };
    x.print();

    Rectangle y{ 4.0 };
    y.print();

    return 0;
}
上のコードから分かるように,member variable宣言とともに{1.0}を用いてinitを行っている.
initializer listを使用してmember変数を初期化しない場合
default値は初期化に直接使用されることを示します
よって、上記コードの出力は以下のようになります
length: 2.0, width: 3.0
length: 4.0, width: 1.0
参照として、非静的メンバーの初期化の初期化方法は次のとおりです.
class A
{
    int m_a = 1;  // ok (copy initialization)
    int m_b{ 2 }; // ok (brace initialization)
    int m_c(3);   // doesn't work (parenthesis initialization)
};
()カッコ初期化はサポートされていません