Initialization List in C++

We know that the constructor initialization list at the constructor definition of the class (or of the derived class) is very important. What is more important is the order in which the list is specified. It is not compulsory to initialize all the variables or members of the class. But it is important that the order of which ever members you initialize is in the same order as the declarations in the class declaration. Let’s see an example below.

class A
{
     int i;
     float j;
     char k;
};

This is a valid constructor definition with initializer list. Note that j has not been initialized, but i and k are in order of declaration as in the class.

A::A() : i(1), k('c')
{
}

But this is not as the order is not the same as that of declarations in the class.

A::A() : k('c'), j(2.2)
{
}

Source: 

http://stackoverflow.com/questions/12222417/why-should-i-initialize-member-variables-in-the-order-theyre-declared-in

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s