Note that there are some explanatory texts on larger screens.

plurals
  1. POWrong return value when access member of class
    primarykey
    data
    text
    <p>I have a class Character and two subclasses Warrior and Wizard.</p> <pre><code>class Character { protected: std::string m_name; Weapon m_weapon; int m_life; public: virtual void hit(Character&amp; cible); }; class Warrior : public Character{ public: Warrior(std::string name); }; class Wizard : public Character{ public: Wizard(std::string name); }; </code></pre> <p>I also have a class Weapon.</p> <pre><code>class Weapon { protected: std::string m_name; int m_damage; public: Weapon(); Weapon(std::string name,int damage, int reloading_time); int get_damage() ; </code></pre> <p>};</p> <p>The hit function is:</p> <pre><code>void Character::hit(Character &amp;cible){ cible.dec_life(m_weapon.get_damage()); } </code></pre> <p>and get_damage is simply:</p> <pre><code>int Weapon::get_damage() { return m_damage; } </code></pre> <p>The problem is that m_weapon.get_damage() returns the value -2 in the hit function for every character (warrior or wizard) even though its Weapon's damage is 10 or 15.</p> <p>Main:</p> <pre><code>int main() { string character_name; cout &lt;&lt; "Warrior 1 : "; cin &gt;&gt; character_name; Warrior character_1(character_name); cout &lt;&lt; endl &lt;&lt; "Wizard 2 : "; cin &gt;&gt; character_name; Wizard character_2(character_name); character_1.hit(character_2); } </code></pre> <p>Weapon Constructor:</p> <pre><code>Weapon::Weapon(std::string name,int damage, int reloading_time){ m_name=name; m_damage=damage; } </code></pre> <p>Warrior Constructor:</p> <pre><code>Warrior::Warrior(string name){ m_name=name; m_life=100; Weapon m_weapon("Rusted Axe",5,0); cout &lt;&lt; endl &lt;&lt; "Warrior " &lt;&lt; m_name &lt;&lt;" created." &lt;&lt;endl; } </code></pre> <p>Wizard Constructor :</p> <pre><code>Wizard::Wizard(string name){ m_name=name; m_mana=100; m_life=100; Weapon m_weapon("Apprentice Wand",10,0); cout &lt;&lt; endl &lt;&lt;"Wizard " &lt;&lt; m_name &lt;&lt;" created."&lt;&lt;endl; } </code></pre> <p>Any idea where I get it wrong?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload