-4

I have a structure with unnamed structure inside. I want to initialize whole structure and it's member structure in class initializer list.

struct Foo {
  int z;
  struct {
    double upper;
    double lower;
  } x, y;
};

class Bar {
  Bar();

  Foo foo;
};

Can this be done?

Also can this structure be initialized "old fashion" way providing a constructor without uniform initialization syntax?

struct Foo {
    Foo() : z(2), x(/*?*/), y(/*?*/) {}
    Foo() : z(2), x.lower(2) {} // doesn't compile
    int z;
    struct {
      double upper;
      double lower;
    } x, y;
};
Eligijus Pupeikis
  • 1,115
  • 8
  • 19
  • 3
    Sure. Did you try and how did you fail? – Rakete1111 Sep 01 '17 at 07:22
  • 1
    You inner struct definition is an **unnamed struct** an anonymous struct is slightly different, see the difference here: https://stackoverflow.com/a/14248127/8051589. – Andre Kampling Sep 01 '17 at 07:25
  • My apologies for confusing unnamed struct with anonymous. I was not aware of the new c++11 uniform initialization syntax. I improved my question regarding initialization without curly braces. – Eligijus Pupeikis Sep 01 '17 at 07:58

2 Answers2

4

If I understand you correctly you want to initialize the struct Foo, which contains an unnamed struct, in the initializer list of Bar:

#include <iostream>

struct Foo {
  int z;
  struct {
    double upper;
    double lower;
  } x, y;
};

class Bar {
public:
  Bar();

  Foo foo;
};

Bar::Bar()
: foo { 1, { 2.2, 3.3}, {4.4, 5.5} }
{

}

int main()
{
    Bar b;

    std::cout << b.foo.z << std::endl;
    std::cout << b.foo.x.upper << std::endl;
    std::cout << b.foo.y.lower << std::endl;
}
Andre Kampling
  • 5,476
  • 2
  • 20
  • 47
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
0

If I understand correctly you want to have a static initialization of the full struct including the inner unnamed struct.

Have you tried something as:

Foo foo { 1,            // z
        {1.1, 2.2},     // x
        {3.3, 4.4}};    // y
Stefano
  • 3,981
  • 8
  • 36
  • 66