In C++ if you don’t provide a constructor for the class the compiler provides one for you (that does nothing):
This, of course, isn’t very useful so typically we write our own constructors to initialise the attributes of our class. However, as soon as you write a (non-default) constructor the compiler stops providing the default constructor:
The normal solution is to write our own default constructor. In C++11 there is syntax to allow you to explicitly create the compiler-supplied constructor without having to write the definition yourself:
So far, this doesn’t seem to have gained us very much; if anything it feels like syntax for the sake of it.
Non-static member initialisation
C++ has, for some time, allowed initialisation of static member variables in the class declaration.
This was allowed because the static member is allocated at compile time. C++11 has extended this notation to include non-static members as well:
What this syntax means is: in the absence of any other initialisation the value of data should be set to 100. This is, in essence, a little bit of syntactic sugar around the MIL to save you having to write the following:
Putting it all together
Combining non-static member initialisation with default constructors allows us to write code like this:
There are possibly two ways to view this: either it’s a new (and uncomfortable) syntax to learn that just adds more variety (and confusion) to the language; or that C++’s default initialisation was ‘broken’ (and we learned to compensate) and this is the syntax that should have always have been.