Alex Blekhman
2010-03-04 15:29:31 UTC
Hello,
Recently I noticed that VC++ 2008 compiler can zero initialize a
class instance with the following code:
class X
{
public:
int n1;
int n2;
};
X x1 = X(); // X::n1 and X::n2 are zeroes.
However, if at least one member of the class is not public, then
no initialization occurs whatsoever:
class X
{
public:
int n1;
private:
int n2;
};
X x2 = X(); // X::n1 and X::n2 are garbage.
Now, according to 8.5/7:
"An object whose initializer is an empty set of parentheses,
i.e., (), shall be value-initialized."
So, the expression "X()" should create temporary copy of X, which
is value initialized. According to 8.5/5:
"To value-initialize an object of type T means:
[...]
- if T is a non-union class type without a user-declared
constructor, then every non-static data member and base-class
component of T is value-initialized;
[...]
- otherwise, the object is zero-initialized"
It seem that the expression "X()" should create an instance of X,
which is zero initialized. Then the declared variable of X should
be copy initialized from this temporary instance.
The question is: why it works with all members being public, and
fails if there is at least one non-public member?
Thanks
Alex
Recently I noticed that VC++ 2008 compiler can zero initialize a
class instance with the following code:
class X
{
public:
int n1;
int n2;
};
X x1 = X(); // X::n1 and X::n2 are zeroes.
However, if at least one member of the class is not public, then
no initialization occurs whatsoever:
class X
{
public:
int n1;
private:
int n2;
};
X x2 = X(); // X::n1 and X::n2 are garbage.
Now, according to 8.5/7:
"An object whose initializer is an empty set of parentheses,
i.e., (), shall be value-initialized."
So, the expression "X()" should create temporary copy of X, which
is value initialized. According to 8.5/5:
"To value-initialize an object of type T means:
[...]
- if T is a non-union class type without a user-declared
constructor, then every non-static data member and base-class
component of T is value-initialized;
[...]
- otherwise, the object is zero-initialized"
It seem that the expression "X()" should create an instance of X,
which is zero initialized. Then the declared variable of X should
be copy initialized from this temporary instance.
The question is: why it works with all members being public, and
fails if there is at least one non-public member?
Thanks
Alex