I have a class say Test with default constructor:
What is the difference between these two cases:
Test class1 = new Test();
Test class2 = new Test;
None. Both fail to compile.
But you probably meant:
Test* class1 = new Test() ;
Test* class2 = new Test ;
I did a test and find that the member variable initialize to 0
in the first case. With second case, the member variable
initialize to garbage. Does the Standard state this
difference?
Yes, in §8.5/7-10. "An object whose initializer is an empty set
of parentheses, i.e., (), shall be value-initialized.[...] If no
initializer is specified for an object, and the object is of
(possibly cv-qualified) non-POD class type (or array thereof),
the object shall be default-initialized; if the object is of
const-qualified type, the underlying class type shall have a
user-declared default constructor. Otherwise, if no initializer
is specified for an object, the object and its subobjects, if
any, have an indeterminate initial value[...]"
Your object is a non-POD class with no user-declared
constructor, so value initialization invokes value
initialization of each of its members, and value initialization
of an int is zero initialization. (Note that if you had defined
a constructor which didn't initialize a, a would have an
indeterminate value after value initialization. Any constructor
you define has precedence.) In the case of default
initialization, the compiler generated constructor is called,
and nothing else; the compiler generated constructor leaves a
uninitialized.
Note that if the class were a POD (a was public), then slightly
different rules apply: both value and default initialization
would zero initialize, but the last "Otherwise" in the citation
of the standard above would apply, so "new Test" would still
leave the object, and its subobjects, with an indeterminate
value.