2

Is it legal to do the following?

#include <iostream>

struct Foo
{
    int bar;
    int baz;
};

int main()
{
    Foo instance = { 5, instance.bar };
    std::cout << instance.baz << std::endl;
}

I think it's not because as far as I know the order of initialization is unspecified and the bar field can be initialized after baz.

Am I right?

https://coliru.stacked-crooked.com/a/ea97713515dd0687

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242

1 Answers1

2

If you liked your conundrum, this is really gonna bake your noodle:

#include <iostream>

struct Foo
{
    int bar=0;
    int baz=1;
};

const int cool(const Foo& f) 
{
    std::cout << "Bar: " << f.bar << " Baz: " << f.baz << std::endl;
    return f.bar;
}

int main()
{
    Foo instance = { 5, cool(instance) };
    std::cout << instance.baz << std::endl;
}

What a previous poster correctly quoted: c++ std draft doc

...all value computations and side effects associated with a given element are sequenced before those of any element that follows it in order.

AndreasT
  • 9,417
  • 11
  • 46
  • 60