Search code examples
c++structconstructorbraced-init-list

Brace initialization of child struct


Is there a way to initialize a child struct using braces by including base struct member variables. I am trying the below but does not compile (Using VS and C++ 20). I don't want to create a constructor and would like to use a one line construction.

struct Base
{
    int n;
};

struct Derived : Base
{
    std::string s;
};

static const Derived d1{ .s = "Hi", { .n = 1 } }; //fails to compile
static const Derived d2{ 1, { "Hi" } };           //fails to compile
static const Derived d3{ 1, "Hi" };
static const Derived d4(1, "Hi");

EDIT: d4, d3 actually compile fine.


Solution

  • This works for me, https://godbolt.org/z/oYWYr5Gc7:

    #include <string>
    
    struct Base {
      int n;
    };
    
    struct Derived : Base {
      std::string s;
    };
    
    // Designated-initializers must be in the order of the member declarations.
    // Base data members precede Derived data members.
    static const Derived d1 = {{.n = 1}, .s = "Hi"};
    
    static const Derived d2{1, {"Hi"}};
    static const Derived d3{ 1, "Hi" };
    
    // It does not work because Derived does not have the constructor.
    // The aggregate initialization should be called with braces (d3).
    // static const Derived d4(1, "Hi");