1

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:

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?

Kevin eyeson
  • 375
  • 4
  • 8
  • 1
    The simple answer is because the initializer list is for initialization. I.e calling constructors. – Taekahn Jun 13 '22 at 02:37
  • @Kevineyeson [Why class data members can't be initialized by direct initialization syntax?](https://stackoverflow.com/questions/28696605/why-class-data-members-cant-be-initialized-by-direct-initialization-syntax) – Jason Jun 13 '22 at 03:22

1 Answers1

3

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

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Thank you! But I'm still confused about why I can't instantiate object directly in class like this `obj inclassobj(6);` – Kevin eyeson Jun 13 '22 at 02:59
  • 1
    @Kevineyeson because the C++ standard simply does not allow that syntax for initializing members. But `obj inclassobj{6};` would work ([demo](https://ideone.com/7vD3gT)) – Remy Lebeau Jun 13 '22 at 04:11