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?
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);
}
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)
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With