Search code examples
c++memoryconstructorinitialization-list

Is the order of variable used in constructor initialization list important?


Consider the below class

class A 
{
int a;
double b;
float c;
A():a(1),c(2),b(3)
{}
}

Do we have to use variables in initialization list in the same order as we declared in class? And Will the order of variables in initialization list has any impact on memory allocation of that class/variables? (consider the scenario, if the class has many bool variables, many double variables etc..)


Solution

  • Do we have to use variables in initialization list in the same order as we declared in class?

    Order of initialization list doesn't have impact on initialization order. So it avoids misleading behavior to use real order in initialization list.

    Problem comes when there is dependencies:

    class A 
    {
      int a;
      double b;
      float c;
      // initialization is done in that order: a, b, c
      A():a(1), c(2), b(c + 1) // UB, b is in fact initialized before c
      {}
    };
    

    Will the order of variables in initialization list has any impact on memory allocation of that class/variables?

    Order of initialization list doesn't have impact on layout or in initialization order.