2

If I have class that has two member data x_ and y_ declared so that x_ is initialized from y_ and y_ has a value then is x_ has an Undefined value? or what?

class Empl {
    public:
        int x_{ y_ };
        int y_{ 10 };
};

int main(){

    Empl e{};
    std::cout << e.x_ << ", " << e.y_ << std::endl;

}

I tried the example on MSVC++ 2105 and got: 0 and 10 while on GCC I got 10 and 10!

So as a result is it undefined behavior to do so?

Alex24
  • 600
  • 2
  • 13
  • 1
    C++ requires (or used to require) `x` initialization first, and then `y` initialization second because that's the order they are declared. GCC is probably optimizing what it sees as a constexpr. As to the UB, it is probable. Compile and run with `-fsanitize=undefined`. – jww Jun 16 '19 at 00:20
  • 3
    they are [initialized in the order they are declared](https://stackoverflow.com/questions/2669888/c-initialization-order-of-class-data-members) – kmdreko Jun 16 '19 at 00:21

1 Answers1

7

So as a result is it undefined behavior to do so?

Yes. The behaviour of reading an indeterminate value is undefined. In this example, y_ has indeterminate value when its value is used to initialise x_, because it is initialised after x_. It is initialised after x_ because members are initialised in order of declaration.

eerorika
  • 232,697
  • 12
  • 197
  • 326