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

Why I can't use constructor initializer list to initialize a in-class struct?

I’m trying to do this:

class test{
    public:
    struct obj{
        int _objval;
    };
    obj inclassobj;
    int _val;
    test(){}
    test(int x):_val(x){}
    test(int x, int y): _val(x), inclassobj._objval(y){}

};

It doesn’t work. Unless I put in-class struct part in to the body of the constructor like this:

test(int x, int y){
    _val = x;
    inclassobj._objval = y;
}

This way works fine. Then I find someone said unless I can give my in-class object it’s own constructor, then I did this, it doesn’t work:

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

class test{
    public:
    struct obj{
        int _objval;
        obj(){}
        obj(int val): _objval(val){}
    };
    obj inclassobj(6);
};

The error pops up at the line where I’m trying to instantiated obj: obj inclassobj(6);
I have totally no idea about this. The first question is why I can’t use constructor initializer list to initialize a in-class struct in this case? If the reason is I need to give that struct a constructor, why the second part is also doesn’t work?

update::
I realize I can use a pointer to initialize the in-class object like this:

class test{
    public:
    struct obj{
        int _objval;
        obj(){}
        obj(int val): _objval(val){}
    };
    obj* inclassobj = new obj(6);
};

But why?

>Solution :

In your 2-param constructor, you can use aggregate initialization of the inner struct, eg:

test(int x, int y): _val(x), inclassobj{y}{}

Online Demo

In your second example, adding a constructor to the inner struct is fine, you just need to call it in the outer class’s constructor member initialization list, eg:

test(int x, int y): _val(x), inclassobj(y){}

Online Demo

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