Search code examples
c++objectconstructorinitializer-list

Object constructor within another constructor?


I'm still fresh to CPP and I'm trying new things with all this free time we have currently. I have 2 separate classes and I want to create an initializer list for both in main... May'be I'm not putting it in the best words, but...

There's this:

class Status
{
public:
    int x, y;
    float angle;
    unsigned short hp;
    bool isActive;
    Status(const int _x, const int _y, const float _angle, const unsigned short _hp, bool _isActive)
        : x(_x), y(_y), angle(_angle), hp(_hp), isActive(_isActive){};
};

And this:

class Hero
{
    std::string name;
    Status status;
    Hero(const std::string _name, Status &status)
        : name(_name), status(x, y, angle, hp, isActive){}; 
    void display()
    {
        std::cout << "Hero:\t" << name << std::endl;
        std::cout << "HP:\t" << Hero::status.hp << std::endl;
        std::cout << "Hero is " << Hero::status.isActive ? " active" : " inactive";
        std::cout << std::endl;
    };

...and I ultimately want to do something like this... Hero h = {"Iron Man", {1, 2, 32.9, 100, true}};

Please guide me, o wise ones...


Solution

  • This code:

    Hero(const std::string _name, Status &status)
        : name(_name), status(x, y, angle, hp, isActive){}; 
    

    should be:

    Hero(const std::string _name, Status status)
        : name(_name), status(status){};
    

    Optionally it could be status(std::move(status)) .

    Also there is a logic error on the line with the conditional operator which has higher precedence than << so you need some parentheses.