Search code examples
c++c++11constructorinitialization-list

Can I check variables in a constructor body that were set in the initialization list?


I have doubts on how the constructor's body works in case of initialization lists. If the value passed by the constructor are not admitted value and an exception needs to be thrown, is it correct to do something like this?

Foo(int a_) : a(a_) {
  if (a>0)
    throw std::invalid_argument("positive value!");
};

I am having doubt on how this is evaluated, in case of more complex situations.


Solution

  • According to cppreference, it is absolutely safe to assume the initializer list will be completed before the 'body' of the constructor is executed (bolding of item 4 is mine):

    The order of member initializers in the list is irrelevant: the actual order of initialization is as follows

    • 1 If the constructor is for the most-derived class, virtual base classes are initialized in the order in which they appear in depth-first left-to-right traversal of the base class declarations (left-to-right refers to the appearance in base-specifier lists)
    • 2 Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list
    • 3 Then, non-static data members are initialized in order of declaration in the class definition.
    • 4 Finally, the body of the constructor is executed

    Now, although cppreference isn't the actual standard, it's normally accurate on such matters.

    EDIT: The draft C++14 (§ 12.6.2) standard (pp. 283-284 of that PDF) confirms what cppreference states. (Yes, I know the OP specified C++11 - but I couldn't get a link to that standard online, and I very much doubt that the standard in that matter has changed between 11, 14 and 17!)