Search code examples
c++constructoraggregate-initialization

How I can keep aggregate initialization while also adding custom constructors?


If I don't define a constructor in a struct, I can initialize it by just picking a certain value like this:

struct Foo {
    int x, y;
};

Foo foo = {.y = 1};

But if I add new default constructor then I lose this feature:

struct Bar {
    int x, y;
    Bar(int value) : x(value), y(value) {}
};

Bar bar1 = 1;
Bar bar2 = {.y = 2}; // error: a designator cannot be used with a non-aggregate type "Bar"

Is it possible to have both ways?

I tried adding the default constructor Bar () {} but it seems to not work either.


Solution

  • Similar to what ellipticaldoor wrote:

    struct FooBase {
        int x = 0, y = 0;
    };
    
    struct Foo : FooBase {
        Foo(int x_) : FooBase{.x = x_} { }
        Foo(FooBase &&t) : FooBase{t} {}
    };
    
    Foo foo = {{.y = 1}};
    Foo foo2{1};