Home > Software design >  When does a struct require a default constructor?
When does a struct require a default constructor?

Time:08-13

I wrote a struct with custom constructor designed to be a data member of a class:

struct HP
{
    int max_hp;
    int hp;
    // HP(){}; it is required for the next class constructor function. Why?
    HP(int max_hp) {
        this->max_hp=max_hp;
        this->hp=max_hp;
    }
};

class Character
{
protected:
    HP hp;

    friend struct HP;

public:
    Character(int hp);
};

Character reports: Error C2512: 'HP': no appropriate default constructor available

Character::Character(int hp){
    this->hp = HP(hp);
}

Where did I implicitly initialize HP such that a default constructor is required? inline?

CodePudding user response:

All class members are initialized before entering the body of the constructor.

Character::Character(int hp)
{ // already too late to initialize Character::hp
    this->hp = HP(hp); // this is an assignment
}

Without a HP default constructor, Character(int hp); cannot initialize its hp member unless it can provide arguments to the HP constructor, and the only way to forward the arguments to the HP constructor is with a Member Initializer List.

Example:

struct HP{
    int max_hp;
    int hp;
    HP(int max_hp): // might as well use member initializer list here as well
        max_hp(max_hp),
        hp(max_hp)
    {
        // no need for anything in here. All done in Member Initializer List
    }
};

class Character
{
protected:
    HP hp;

    friend struct HP; // not necessary. HP has no private members.

public:
    Character(int hp);
};

Character::Character(int hp):
        hp(hp)
{
}
  • Related