Initializer lists, better or worse?

This is a discussion on Initializer lists, better or worse? within the C++ Programming forums, part of the General Programming Boards category; Which would be faster and more efficient, using an initializer list, or setting variables the traditional way (this->x = x ...

The result of all that is that you can't change what a reference refers to. rInt refers to num1 and that is all it will ever refer to, and doing something to rInt is the same as doing it to num1 directly. In order to set which variable a reference refers to, you have to initialize the reference variable when you declare it:

Code:

int& rInt = num1;

If you don't initialize a reference variable when you declare it, the reference variable won't be able to refer to anything. Here is an example of that:

Code:

int age = 23;
int& rAge;
rAge = age; //error

That is relevant to constructors and initializer lists because a constructor first constructs the object before it gets to the opening brace of the constructor body. Therefore, all the member variables have been created by that point, and a member variable that is a reference type will be created so that it doesn't refer to anything. That means in the constructor body it's too late to try and assign a variable name to the reference. On the other hand, using an initializer list causes the listed variables to be initialized with the specified values as they are created.

>Which would be faster and more efficient
Who cares? Micro-optimization like this is silly in the extreme. There are plenty of other ways to get a bigger performance improvement. That said, initializer lists will sometimes be required, sometimes be better than explicit assignment, and will never be worse. The logical conclusion is to use initializer lists unless you have a good reason not to.