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?
To initialize a class member variable, put the initialization code in a static initialization block, as the following section shows. To initialize an instance member variable, put the initialization code in a constructor.
In C++, class variables are initialized in the same order as they appear in the class declaration. Consider the below code. The program prints correct value of x, but some garbage value for y, because y is initialized before x as it appears before in the class declaration.
No! We cannot initialize a structure members with its declaration, consider the given code (that is incorrect and compiler generates error).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With