Initializing default values in a struct

C++

C++ Problem Overview


If I needed to initialize only a few select values of a C++ struct, would this be correct:

struct foo {
    foo() : a(true), b(true) {}
    bool a;
    bool b;
    bool c;
 } bar;

Am I correct to assume I would end up with one struct item called bar with elements bar.a = true, bar.b = true and an undefined bar.c?

C++ Solutions


Solution 1 - C++

You don't even need to define a constructor

struct foo {
    bool a = true;
    bool b = true;
    bool c;
 } bar;

To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.

Solution 2 - C++

Yes. bar.a and bar.b are set to true, but bar.c is undefined. However, certain compilers will set it to false.

See a live example here: struct demo

According to C++ standard Section 8.5.12: >if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value

For primitive built-in data types (bool, char, wchar_t, short, int, long, float, double, long double), only global variables (all static storage variables) get default value of zero if they are not explicitly initialized.

If you don't really want undefined bar.c to start with, you should also initialize it like you did for bar.a and bar.b.

Solution 3 - C++

You can do it by using a constructor, like this:

struct Date
{
int day;
int month;
int year;

Date()
{
    day=0;
    month=0;
    year=0;
}
};

or like this:

struct Date
{
int day;
int month;
int year;

Date():day(0),
       month(0),
       year(0){}
};

In your case bar.c is undefined,and its value depends on the compiler (while a and b were set to true).

Solution 4 - C++

An explicit default initialization can help:

struct foo {
    bool a {};
    bool b {};
    bool c {};
 } bar;

Behavior bool a {} is same as bool b = bool(); and return false.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoe WilcoxsonView Question on Stackoverflow
Solution 1 - C++Erik van VelzenView Answer on Stackoverflow
Solution 2 - C++taocpView Answer on Stackoverflow
Solution 3 - C++NicolaView Answer on Stackoverflow
Solution 4 - C++AnamnianView Answer on Stackoverflow