Home > Back-end >  Is referencing a member during Initialization valid?
Is referencing a member during Initialization valid?

Time:11-21

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

CodePudding user response:

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.

  • Related