I found many articles explaining the difference between "default-initialization and value-initialization" but in fact I didn't understand clearly.
Here's an example:
class A{
public:
int x;
};
int main(){
A a;// default initialization so x has undefined value.
A b = A(); // value initialization so x is a scalar thus it is value initialized to 0
}
Above it is OK as I guess but here:
int value = 4; // is this considered a value-initialization?
Please help me understand the major differences between the two forms of initializations.
A a;is default initialization, as the effect the default constructor ofAis used for initialization. Since the implicitly-generated default constructor ofAdoes nothing,a.xhas indeterminate value.A()is value initialization,Note the difference with default initialization,
Ahas an implicitly-defined default constructor, and the object is zero-initialized; so the data memeberxof the temporary objectA()will be initialized to0.A b = A();is copy initialization, in conceptbis initialized from the temporary objectA(), sob.xwill be initialized to0too. Note that because of copy elision, since C++17bis guaranteed to be value-initialized directly; the copy/move construction is omitted.int value = 4;is copy initialization too.valuewill be initialized to4.