On Jul 17, 12:03 pm, Lionel B <m...@privacy.netwrote:
Quote:
This always confuses me. In the example below I would like x to be zero-
initialised on default construction of a struct A object (there is no
other initialisation/construction code required for default
construction). Which form is most appropriate?
Quote:
struct A
{
double x;
Quote:
// first form
// No user-supplied default constructor
Does nothing...
Quote:
// second form
A() {}
Does nothing...
Quote:
// third form
A() : x() {}
Either "value initializes" or "default initializes" x, according
to which version of the standard you refer to. In the case of a
POD type like double, there's no difference, however; both mean
that x will be "zero initialized" (which is the equivalent of
"x(0)"; i.e. it initializes the value with the results of
converting the integral constant 0 to the appropriate type).
This features was added in the 1998 standard; it wasn't present
in pre-standard C++, and some very old compilers might not
implement it. (In pre-standard C++, it did nothing, like the
two previous versions.)
Quote:
// fourth form
A() : x(0.0) {}
Initializes x with 0.0. If that's what you want, then this is
the most appropriate form. (The "x()" form might be more
appropriate, of course, for more complicated types, or in a
template.)
Quote:
void foo()
{
A a;
/* do stuff, assuming a.x == 0.0 */
}
Quote:
Could some kind soul also point me to the relevant entry in
the standard?
Which version of the standard:-)? The different types of
initialization are described in detail in §8.5, from about
paragraph 5 on. The details do differ depending on the version
of the standard, however. (I think the difference is really
only relevant for class types with non-trivial compiler
generated constructors, but I wouldn't swear to it.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34