Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default initialization confusion

Tags:

c++

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?

like image 967
NoobOverflow Avatar asked May 28 '26 19:05

NoobOverflow


2 Answers

The quote seems to be in wrong context. A variable can have at least 3 states:

  1. Default initialized: Variable is initialized inside the constructor based on argument or no argument. Value initialized is a special case of this type
  2. In-class initialized: The C++11 feature which you have presented in your code
  3. Uninitialized: Variable's initialization is not addressed anywhere and it can contain any garbage value. Some compilers may automatically make it 0 or give a warning
like image 50
iammilind Avatar answered May 30 '26 10:05

iammilind


The 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.

like image 25
Dietmar Kühl Avatar answered May 30 '26 08:05

Dietmar Kühl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!