In my C++ Primer, 5th Edition, they say on page 43 about default initialization (emphasis mine):
The value of an object of built-in type that is not explicitly initialized depends on where it is defined. Variables defined outside any function body are initialized to zero.
Later, on page 73, they define a new class like this:
struct Sales_data {
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
This is supposed to provide an example of the new standard's in-class initializers. In this case, units_sold and revenue will be initialized to zero. If they are not, they say, the variables will be default-initialized.
But this is my question: What is the point of this in-class initialization? What's wrong with letting them just default-initialize? The reason I ask is that they already mentioned that variables defined outside any function body are initialized to zero, and in this case, these variables are not inside any function - they are in a class definition. So the default-initialization should initialize these variables to zero, shouldn't it?
The quote seems to be in wrong context. A variable can have at least 3 states:
0 or give a warningThe first statement about "Variables defined outside any function body" refers to objects with static linkage, i.e., variables declared in namespaces: These are zero initialized. The members in the struct get initialized wherever this struct lives. If it lives on the stack or is allocated on the heap, the built-in variable won't get initialized without the assignments, e.g., when used like this:
void f() {
Sales_data data;
}
Even without the initialization in the declaration, they would get zero-initialized if the struct is used like this, though:
Sales_data global; // <--- the "outside any function body" case
void f() {
Sales_data data0 = {};
Sales_data data1 = Sales_data();
Sales_data data2{};
}
However, these all require cooperation by the user of the struct and initializing them explicitly makes sure the values are set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With