c++ - Wrong return value when access member of class -
i have class character , 2 subclasses warrior , wizard.
class character { protected: std::string m_name; weapon m_weapon; int m_life; public: virtual void hit(character& cible); }; class warrior : public character{ public: warrior(std::string name); }; class wizard : public character{ public: wizard(std::string name); };
i have class weapon.
class weapon { protected: std::string m_name; int m_damage; public: weapon(); weapon(std::string name,int damage, int reloading_time); int get_damage() ;
};
the hit function is:
void character::hit(character &cible){ cible.dec_life(m_weapon.get_damage()); }
and get_damage simply:
int weapon::get_damage() { return m_damage; }
the problem m_weapon.get_damage() returns value -2 in hit function every character (warrior or wizard) though weapon's damage 10 or 15.
main:
int main() { string character_name; cout << "warrior 1 : "; cin >> character_name; warrior character_1(character_name); cout << endl << "wizard 2 : "; cin >> character_name; wizard character_2(character_name); character_1.hit(character_2); }
weapon constructor:
weapon::weapon(std::string name,int damage, int reloading_time){ m_name=name; m_damage=damage; }
warrior constructor:
warrior::warrior(string name){ m_name=name; m_life=100; weapon m_weapon("rusted axe",5,0); cout << endl << "warrior " << m_name <<" created." <<endl; }
wizard constructor :
wizard::wizard(string name){ m_name=name; m_mana=100; m_life=100; weapon m_weapon("apprentice wand",10,0); cout << endl <<"wizard " << m_name <<" created."<<endl; }
any idea wrong?
nowhere in code see numbers 10
, 15
. how expect program know specific weapon's damage supposed 10
or 15
?
according code, class weapon
has constructor accepts weapon's damage value. never use constructor. instead, seem constructing m_weapon
members using default constructor of weapon
class, leaves garbage in m_damage
field.
you have develop way perform meaningful initialization of m_weapon
objects. @ point seem hoping compiler somehow telepathically figures out damage values various weapon objects. compilers cannot that.
edit: in constructors construct local m_weapon
object, has absolutely no relation member m_weapon
object. member m_weapon
objects remain uninitialized (i.e. default initialized garbage in m_damage
). not possible perform initialization of member subobject constructor body. member subobjects can initialized constructor initializer list (read in c++ book or search). on top of that, allowed initialize immediate members of class, meaning m_weapon
can initialized character
's constructor. not possible warrior
's or wizard
's constructor.
Comments
Post a Comment