I wonder if there is a reason why we can't initialize members at their declaration.
class Foo
{
int Bar = 42; // this is invalid
};
As an equivalent of using constructor initialization lists.
class Foo
{
int Bar;
public:
Foo() : Bar(42) {}
}
My personal understanding is that the above example is much more expressive and intentional. Moreover this is a shorter syntax. And I don't see any possibility of confusion with other language elements.
Is there any official clarification about this?
The initialization of non-static members could not be done like this prior to C++11. If you compile with a C++11 compiler, it should happily accept the code you have given.
I imagine that the reason for not allowing it in the first place is because a data member declaration is not a definition. There is no object being introduced. If you have a data member such as int x;
, no int
object is created until you actually create an object of the type of the class. Therefore, an initializer on this member would be misleading. It is only during construction that a value can be assigned to the member, which is precisely what member initialization lists are for.
There were also some technical issues to iron out before non-static member initialization could be added. Consider the following examples:
struct S {
int i(x);
// ...
static int x;
};
struct T {
int i(x);
// ...
typedef int x;
};
When these structs are being parsed, at the time of parsing the member i
, it is ambiguous whether it is a data member declaration (as in S
) or a member function declaration (as in T
).
With the added functionality, this is not a problem because you cannot initialize a member with this parantheses syntax. You must use a brace-or-equal-initializer such as:
int i = x;
int i{x};
These can only be data members and so we have no problem any more.
See the proposal N2628 for a more thorough look at the issues that had to be considered when proposing non-static member initializers.
The main reason is that initialization applies to an object, or
an instance, and in the declaration in the class there is no
object or instance; you don't have that until you start
constructing.
There's been some evolution in this regard. Already, at the
very end of standardization of C++98, the committee added the
possibility to do this for static const members of integral
type---mainly because these can be used in contexts where the
compiler must be able to see the initialization. In C++11, the
language has been extended to allow specifying an initializer in
the declaration, but this is just a shorthand—the actual
initialization still takes place at the top of the constructor.
When two or more objects(instance of the class) are declared, those objects share these data members. so value can be initialized with the help of constructor. so we can't initialize the class members during declaration.