Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 438
helpermethod Avatar asked Mar 01 '11 10:03

helpermethod


1 Answers

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.

like image 134
sharptooth Avatar answered Oct 25 '22 14:10

sharptooth