Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading