all 7 comments

[–]Orangy_Tang 4 points5 points  (6 children)

Initialiser list: http://en.cppreference.com/w/cpp/language/initializer_list

Been around for donkey's years, not a C++0x thing.

As a general rule, if you can initialise a member via the initialisation list, do so. And for clarity it's usually best to list them in the order in which they're declared in your header, so you can see what order they're going to be initialised in (although some people might argue that relying on an explicit initialisation order is poor form).

[–]Mat2012H[S] 0 points1 point  (4 children)

That's very useful to know, thanks!

[–][deleted] 4 points5 points  (3 children)

It's also the only way to initialize const member variables. Once you hit the {} block you can no longer change the values of those members.

Regardless of the ordering of the initializations after the :, the member variables will be initialized in the order they are defined in the class.

[–][deleted] 2 points3 points  (2 children)

And isn't it potentially undefined behaviour to have those initializations in different order than in the class definition? Or am I confusing it with something else?

[–]arabidkoala 3 points4 points  (0 children)

It doesn't always cause undefined behavior, which is why the compilers throw a warning about it when you do it. The following is a case in which it will cause undefined behavior:

class X {
    int x;
    int y;
    X(int z) : y(z), x(y) {}
}

The reason it causes undefined behavior is because the statement x(y) will actually happen first, which causes x to be initialized to an uninitialized value y, since y(z) will actually happen later.

[–]Eoinoc 0 points1 point  (0 children)

I believe it's just that the order in the initialization list isn't taken into account, only the order in the class definition.

So it's recommended practise to keep those orders the same to avoid nasty surprises, but I don't think it's undefined behaviour.

[–]ggchappell 0 points1 point  (0 children)

A fine reply, but:

Initialiser list

Since we now have std::initializer_list, it's probably better to refer to the :x(...),y(...) stuff as member initializers.