C++ Initialization lists - I don't get it

helpermethod picture helpermethod · Mar 1, 2011 · Viewed 33.2k times · Source

In Effective C++, it is said that data elements in the initialization list need to be listed in the order of their declaration. It is further said that the reasoning for this is that destructors for data elements get called in the reverse order of their constructors.

But I just don't see how this could be a problem...

Answer

sharptooth picture sharptooth · Mar 1, 2011

Well consider the following:

class Class {
    Class( int var ) : var1( var ), var2(var1 ) {} // allright
    //Class( int var ) : var2( var ), var1(var2 ) {} // var1 will be left uninitialized

    int var1;
    int var2;
};

The second (commented out) constructor looks allright, but in fact only var2 will be initialized - var1 will be initialized first and it will be initialized with var2 that is not yet initialized at that point.

If you list initializers in the same order as member variables are listed in the class declaration risk of such errors becomes much lower.