Caio Gomes
Caio Gomes

Reputation: 768

Initialization list with items declared but not initialized

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.

Upvotes: 3

Views: 1970

Answers (2)

HugoTeixeira
HugoTeixeira

Reputation: 4884

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.

Upvotes: 1

Swordfish
Swordfish

Reputation: 13134

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.

Upvotes: 5

Related Questions