Search code examples
c++constructorinitializer-list

Order of initialization of class member variables


Consider the following code snippet:

class A
{
public:
    A(int a, int b) : j(a), i(j + b) {}
    int i, j;
};

int main()
{
    A a(10, 20);
    std::cout << a.i << " " << a.j << std::endl;
    return 0;
}

The standard says that the order of initialization of the member variables is the order in which they are declared. In this case, i will be initialized before j. Since j isn't initialized yet, i = *a garbage value* + 20, and then j is initialized with 10.

The code prints 20 10.

i.e., j was considered to be 0 when calculating i.

Does the standard guarantee to use default values for built-in types in such a scenario? Or is it just that the garbage value happened to be 0? Or is it undefined behavior?


Solution

  • Does the standard guarantee to use default values for built-in types in such a scenario?

    No. The value is indeterminate in this case.

    Or is it undefined behavior?

    Yes. The behaviour of reading an indeterminate value is undefined (except for narrow character types IIRC).