Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define `health` and `maxHealth` in one object, when `healt` can't be higher than `maxHealth`?

I have a class called Warrior that has uint m_health and uint m_maxHealth attributes. I want my constructor to take parameters Warrior(uint health, uint maxHealth).

Now I've studied C++ a lot and I know all the syntax etc, but it's hard to find tutorials on how to use the stuff etc. so I don't really know how should I define health and maxHealth when health obviously can't be higher than maxHealth :/

Here are few methods I thought of:

// method 1
Warrior::Warrior(uint health, uint maxHealth) :
    m_health((health > maxHealth) ? maxHealth : health),
    m_maxHealth(maxHealth)
{}

// method 2
Warrior::Warrior(uint health, uint maxHealth) :
    m_maxHealth(maxHealth)
{
    if (health > maxHealth) {
        m_health = maxHealth;
    }
    else {
        m_health = health;
    }
}

I'm sure there are other ways too. Sorry if this is just an opinion question, but if there's a "preferred" way in C++, what would it be?

like image 517
Patrik Lippojoki Avatar asked Dec 17 '25 19:12

Patrik Lippojoki


2 Answers

If you intended to set the health during the game you might want to consider something like this:

Warrior::Warrior(unsigned int health, unsigned int maxHealth) :
    m_maxHealth(maxHealth)
{
    setHealth(health);
}

void Warrior::setHealth(unsigned int health)
{
    m_health = std::min(health, m_maxHealth);
}
like image 153
zenpoy Avatar answered Dec 20 '25 10:12

zenpoy


There is a "better" way, depending on your definition of better. (And I'm guessing you mean "shorter" here)

Warrior::Warrior(unsigned int health, unsigned int maxHealth) :
    m_health(std::min(health, maxHealth)),
    m_maxHealth(maxHealth)
{
}
like image 31
user123 Avatar answered Dec 20 '25 11:12

user123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!