Value initialization on explicit constructor call in C++? [duplicate]
-
27-06-2021 - |
Question
Possible Duplicate:
What do the following phrases mean in C++: zero-, default- and value-initialization?
There are multiple places where people have said that an explicit call to the class constructor results in value initialization [when no used-defined constructors exist] and that this is not done by the default constructor [which is a do-nothing constructor] but is something completely different.
What happens actually if no constructor is called OR What is value initialization in this case ?
Solution
Firstly, what happens actually if no constructor is called
A constructor for a class-type is always called when an object is constructed, be it user-defined or compiler-generated. The object is initialized, but the members can remain un-initialized. This makes the second part of the question obsolete.
Second, is there documentation that supports/mentions/explains this behaviour ?
The all-mighty standard.
OTHER TIPS
This is only true for aggregates: Consider this:
struct Holder
{
Aggregate a;
NonAggr n;
Holder(int, char) : a(), n() { }
Holder(char, int) { }
};
Holder h1(1, 'a');
Holder h2('b', 2);
Suppose Aggregate
is an aggregate type. Now h1.a
is value-initialized, which value-initializes each member, while h2.a
is default-initialized, which default-initializes each member. The same holds for the n
member, but if NonAggr
is a non-aggregate class type, its default constructor will always be called.