Jerry said:
Difference ctors might need to initialize a
variable differently. As-is, the rule is consistent: non-static
members are initialized on the ctor. I doubt that the rules could be
kept nearly this consistent otherwise. Just for example, if you had
something like:
class X {
int x=0;
public:
X() : x(1) {}
};
how would you deal with it? Consider it ill-formed (keeping in mind
that the class definition will often be visible in places that the
ctor isn't)? Start with 0 and then assign 1? Start with 1 and then
assign 0? What would you do if (for example) instead of an int, this
was an instance of some other class that only supported initialization
and NOT assignment?
Ultimately, I suspect each of these questions _could_ be answered, but
doing so would probably lead to quite a few more. In the end, all the
questions might have answers, but I doubt anybody has gone to the
trouble of figuring out for sure -- most of the people on the
committee are pretty busy to start with, so in general, committee work
gets prioritized, and something that adds a lot of questions but
little or no new utility is likely to get quite a low priority.
Admittedly, this could be naive, but it seems to me to be
straightforward to avoid ambiguity without much to consider. The
compiler will flag an error if initialization is specified at both the
declaration and an initialization list. Hence, programmers can use
simultaneous declaration/initialization only for parameters for which
it makes sense (i.e. for variables which the author intended to be
unchangable). It seems preferable to having a static member, since
the value is right at the same location as the declaration.
If the data member wasn't an int, and didn't have an assignment
operator, just initialize it in the way that you would any object at
declaration:
class X
{
int x(0);
// ...
};
This is not to suggest that this idea will be welcome or noticed by
any significant number of people (or any at all), especially
overworked standards committe people. Just to say that there don't
seem to be any real difficulties with it.
Some might think it less clear to have the initialization value
separate from the constructor, but there are some parameters
for which it just makes sense for value to be readily apparent
when the variables declaration is seen. Mostly constants, or
near-constants. If the class definition is seen as a "table of
contents", or "map", of the class structure, it makes sense to have
those values right up front. Easier to look up compared to tucking it
away in constructors somewhere. And it simplifies the constructor's
initialization list.
Fred