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


i have class called warrior has uint m_health , uint m_maxhealth attributes. want constructor take parameters warrior(uint health, uint maxhealth).

now i've studied c++ lot , know syntax etc, it's hard find tutorials on how use stuff etc. don't know how should define health , maxhealth when health can't higher maxhealth :/

here few methods 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 other ways too. sorry if opinion question, if there's "preferred" way in c++, be?

i put assertion or throw exception in case precondition not met:

warrior::warrior(uint health, uint maxhealth) :     m_health(health),     m_maxhealth(maxhealth) {     assert(health <= maxhealth);      // or throw exception     throw std::logic_error("explanation"); } 

i mean, rational decide caller value take? if caller puts health value bigger maxhealth - it's violation of class logic, propose fail , inform caller this. should problem in software, think it's not desirable hide it.

exception or assertion explicit mechanism find , recognise such problems early.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -