Search code examples
c++constructorinitializationdefault-constructordesignated-initializer

How to designated initialize a C++ struct that has a construcotr?


I have a very large struct that has customized copying constructor, customized moving constructor, customized moving assignator, and customized copying assignator, but I also need to use Designated Initialization syntax somewhere to initialize it, because it is very large, while I just want to initialize only few fields of it and let the rest fields to keep default values.

For example:

struct SA_t {
    int a;
    int b;
    int c;
};

int main() {
    SA_t sa1 { .a = 2, .b = 3, .c = 4,};  // no problem
    return EXIT_SUCCESS;
};

But when I added a customized constructor for it, I can NOT use Designated Initializing method at all.

struct SA_t {
    SA_t() {
        a = 0;
        b = 1;
        c = 2;
    };

    int a;
    int b;
    int c;
};

int main() {
    SA_t sa1 { .a = 2, .b = 3, .c = 4,};  /* no matching function for call to ‘SA_t::SA_t(<brace-enclosed initializer list>)’ */
    return EXIT_SUCCESS;
};

Is there a way, I can keep the customized constructor and use Designated Initialization syntax at same time?


Solution

  • There isn't. Designated initializers work only for aggregates. Aggregates are types that satisfy a few conditions, notably:

    • no user-declared or inherited constructors