3

I have a question regarding initialization lists when I'm not initializing all the items.

Let's say I have the following code:

class Example {
  int a, b, c;

  Example() : a(1), b(2), c(3) {}
}

I'm aware that the order of initialization of members is defined by their order of declaration, not by the order in which they are listed in the initialization list, but, what if I don't have b in the initialization list as in the following?

class Example {
  int a, b, c;

  Example() : a(1), c(2) {}
}

Will a be initialized with 1, b with an undefined value and c with 3? Will I get an undefined behavior because I'm not calling the initialization list strictly with the order I'm declaring? Or none of this?

I'm asking this because I have a class with a lot of data and I want to make sure some of it have an initial value, but I don't need to initialize all of it.

Caio Gomes
  • 681
  • 1
  • 11
  • 23

2 Answers2

5

Not initializing a member in the initializer list won't lead to undefined behaviour. Reading it is undefined behaviour. A not initialized int will be default-initialized which leaves it in an indeterminate state.

Swordfish
  • 12,971
  • 3
  • 21
  • 43
1

The idea of undefined behavior depends on the context here. The point is that your code should NOT trust the value of non-initialized variables. For example, consider this piece of code (extended from your example):

#include <iostream>

class Example {
public:
    int a, b, c;
    Example() : a(1), c(2) {}
};

void print(const Example& e) {
    std::cout << e.a << ' ' << e.b << ' ' << e.c << '\n';
}

int main()
{
    Example e, f, g;
    print(e);
    print(f);
    print(g);
    return 0;
}

When I run it, I get:

1 32766 2
1 0 2
1 0 2

So clearly the value of b should not be trusted. You should also get a warning message that says:

Constructor does not initialize these fields: b

Considering that it is a good practice to clean up warning messages from the code, you shouldn't develop serious project with this approach.

HugoTeixeira
  • 4,674
  • 3
  • 22
  • 32
  • I get it, but what if I have let 20 properties in my class and I just need to initialize 2? The approach is to make a big initialization list and initialize all of these properties? – Caio Gomes Nov 07 '18 at 23:52
  • 1
    @CaioGomes as long as you don't read uninitialized data you are fine! – Swordfish Nov 07 '18 at 23:54