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.
- Practice makes perfect, part 3 – Idiomatic kata - February 27, 2020
- Practice makes perfect, part 2– foundation kata - February 13, 2020
- Practice makes perfect, part 1 – Code kata - January 30, 2020
Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry.
He specialises in C++, UML, software modelling, Systems Engineering and process development.
While the "default" idea for constructors is nice, I never really understood why C++ abandoned the do-nothing constructor just because of the existence of some other, non-default constructor, or why C++11 allowed this behaviour to continue. There is a choice of two more logical behaviours:
(1) Keep the do-nothing default unless it is overloaded. In this case, the new "= default" syntax would be redundant, but nicely explicit, nevertheless.
(2) Never provide an automatic do-nothing default constructor for a class, though keep it for struct (for C compatibility). In this case, the new syntax would often be useful.
The initialisation syntax was certainly inconsistent, depending, as it did, on what was being initialised. The new syntax is better.
P.S. The last paragraph in my previous comment is spurious and relates (sort of) to something not covered in the article. Sorry!