PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

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

 July 08, 2022     c++, class, constructor     No comments   

Issue

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?


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



Answered By - Remy Lebeau
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing