Best way to initialize a property?

I think I may be abusing virtual function.

class Mob: public Sprite{
    int _HP;
    virtual int getMaxHP() = 0;
    bool init() override{
          if(!Sprite::init()) return false;
          _HP = getMaxHP();
          return true;
    }
}
class Zombie: public Mob{
      int getMaxHP() override{
            return 100;
      }
}

Does Zombie inherit from Mob? I don’t think you’ve put the full code here.

Yes, Zombie inherit from Mob. The full code is large and not helpful to this post.

If you’re taking the path of inheritance I would recommend using dependancy injection

class Mob
{
protected:
    bool init(int maxHP)
    {
          if(!Sprite::init()) return false;
          _HP = maxHP;
          return true;
    }
private:
    int _HP;
}
class Zombie : public Mob
{
protected:
    bool init()
    {
        if(!Mob::init(100)) return false;
        return true;
    }
}

This approach:

  • allows the value to come from anywhere (config file),
  • allows the value to be variable (some zombies are stronger than others)
  • explicitly declares that a Mob requires a maxHP to function

Looking forward I’d suggest creating config objects to clean up injection:

struct MobConfig
{
    int maxHealth;
    float speed;
    float aggroRange;
}

struct ZombieConfig
{
    MobConfig mobConfig;
    std::string spriteFile;
    std::string groanSoundFile;
}

Hope this helps

(Edit: init functions changed from private to protected)

1 Like

This looks okay, Mob is abstract so you can’t ever create an instance of it. If you’re doing it this way you would need an init function in Zombie as well that calls Mob init the same way Mob calls Sprite init.

When the Zombie class calls mob init it will use the getMaxHP from the zombie class.

Thanks. I have another problem. I have difficulty designing the API of equipments.

class Equipment{
      virtual void attach( Player* )=0;
      virtual void detach( Player* )=0;
}
class Axe: public Equipment{
      void attach( Player* player) override{ player.addStrength(10); }
      void detach( Player* player) override { player.addStrengh( -10);}
}
class Player{
      void equip( Equipment* e) { e->attach(this); }
}

Can you recommand some blogs or game project?

I may be wrong, but by the snippets you posted it seems that what might help you the most is reading a good c++ tutorial and some other good tutorials on how to design classes. Even if you think you don’t need them, check them out anyway: there’s always something new to learn if you find the right resources.