2

I have a struct that contains multiple members.
these members should be constructed using another member.
Is accessing this other member for the initialization of the members valid, or am I invoking UB this way?

struct Data {
    int b;
};

struct Bar {

    Bar(Data& d): a(d.b){
    }
    int a;
};

struct Foo {
    Data data;
    Bar b;
};

int main() {
    Foo f {.data = Data(), .b = Bar(f.data)}; // b is constructed using f.data!
}

https://godbolt.org/z/fajPjo6oa

Raildex
  • 3,406
  • 1
  • 18
  • 42

1 Answers1

1

Members are initialized in the order they are declared in the struct/class and you can validly reference other members during initialization, as long as they have already been initialized at that point. This holds regardless of how initialization is performed.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70