3

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?

1
  • 1
    The data members would not be initialized to 0, so either the quote is wrong, or there is some missing context. Commented Nov 17, 2012 at 13:21

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.