2

Is assigning m_B to m_A in the constructor below legal, provided that m_B is declared after m_A?

class C {
    int m_A, m_B;
    C() : m_A(0), m_B(m_A) {}
};
Michael
  • 5,775
  • 2
  • 34
  • 53

1 Answers1

2

Yes, it is legal to assign a member to another member in a constructor. There is an example in the standard (§ 15.6.2/15 )

class X {
    int a;
    int b;
    int i;
    int j;
public:
    const int& r;
    X(int i): r(a), b(i), i(i), j(this->i) { }
};

Note that the data members are initialized in the order they are declared in the class definition. The order of the member initializers doesn't matter. So, the below is valid

class C {
    int m_A, m_B;
    C() : m_B(m_A), m_A(0) {}     // Swapped the member initialization order.
};

but this isn't valid

class C {
        int m_B, m_A;             // Swapped the declaration order.
        C() : m_B(m_A), m_A(0) {}
    };
haccks
  • 104,019
  • 25
  • 176
  • 264
  • Does the order of members matter? Or the order they appear in on initializer list? – orhtej2 Aug 13 '18 at 18:00
  • 3
    They're initialized in the order of declaration in the class definition, regardless of the order of the initializer list. See https://en.cppreference.com/w/cpp/language/initializer_list#Initialization_order – alter_igel Aug 13 '18 at 18:06
  • 1
    @orhtej2; § 15.6.2/13.3: *Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers)* – haccks Aug 13 '18 at 18:09
  • 1
    @orhtej2; Added example to make it more clear. – haccks Aug 13 '18 at 18:18