Vinay
Vinay

Reputation: 188

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..)

Upvotes: 2

Views: 1486

Answers (3)

Jarod42
Jarod42

Reputation: 217085

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.

Upvotes: 5

songyuanyao
songyuanyao

Reputation: 172864

First,

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

No, but you'd better to do so to avoid confusion. Because the order of member initializers in the list is irrelevant.

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

Second,

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

No, because it doen't matter at all.

Upvotes: 4

Alexcei Shmakov
Alexcei Shmakov

Reputation: 2343

Variables will initialiaze in the order of declaration in the class.

The order of variables in initializion list does not affect.

In our example the order of initializtion variables will next: a, b, c

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

Not effect.

Upvotes: 2

Related Questions