Reputation: 826
Assuming my knowledge of both the below methods for creating an object calling the default constructor(provided by the compiler) is true.
class A
{
int a,b;
//No programmer defined constructor
}
...
A o1; //Implicit Call I believe
A o2 = A(); //Explicit Call
Why does A o2 = A();
causes the members(a,b) of object o2
to initialize itself with default values(0) but not A o;
(they are initialized with garbage values) ? Is it undefined behavior?
Upvotes: 4
Views: 4332
Reputation: 35
In both the cases default constructor provided by compiler will be called. Most likely c++ compiler initializes value to some garbage value. c++ compiler will not initialize the value to 0 in case of default constructor being called, unless already the memory is dumped with zeros. I tried this scenario , I did not see any difference in the value assigned for a and b in both the objects.
Upvotes: -2
Reputation: 55887
Quotes are from Standard p8.5/1
There is no user-defined constructor here, so, compiler will use the default one. And default constructor will not initialize members with zeros.
If no initializer is specified for an object, the object is default-initialized.
To default-initialize an object of type T means:
If T is a (possibly cv-qualified) class type (Clause 9), constructors are considered. The applicable constructors are enumerated (13.3.1.3), and the best one for the initializer () is chosen through overload resolution (13.3). The constructor thus selected is called, with an empty argument list, to initialize the object.
In second case will be value-initialization.
An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.
To value-initialize an object of type T means:
if T is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;
To zero-initialize an object or reference of type T means:
if T is a (possibly cv-qualified) non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits;
Upvotes: 6