-1

Rather new to C++, though I have learned java. Below the code is suppose to calculate the player health after taking damage assuming they are vulnerable. The problem is that the spellFireDamage is not lowering the player health while poisonDamage is. I looked up and learned overloading but the damage with two parameters is not working correctly? Does this need something to do with overloading that I am doing wrong? How can I fix this? Why is this correctly working for the function with only one parameter? Thanks in advance

`#include <iostream>

using namespace std;

int damage(int spellsDamage) {
    return(spellsDamage*3+5);
}

int damage(int health, int spellsDamage) {
    return (health - (spellsDamage*3+5));
}

int main(){
    int spellFireDamage = 3;
    int spellPoisonDamage = 2;
        int playerHealth = 100;
    bool playerVulnerable = true;
    

    //do something if vulnerable is true
    if (playerVulnerable) {
        damage(playerHealth, spellFireDamage);
        cout << "player health after fire attack" << endl;
        cout << playerHealth << endl;
        playerHealth = playerHealth - damage(spellPoisonDamage);
        cout << "player health after poison attack" << endl;
        cout << playerHealth << endl;
    }
    else {
        cout << "bruh" << endl;
    }
    

        return 0;
}
`

If I pass just one parameter for spellFireDamage (like spellPoisonDamage) it works correctly, but I want my code to be as simple as possible and still want to know why when I pass two operators my function works as not intended. I looked up and it had something to do passing by reference, but I do not quite get it. Please explain how I can fix this in the most simple/clean way! Thank you!

loltkyx
  • 11
  • 5
    When you do `damage(playerHealth, spellFireDamage);`, what do you expect to happen? You're not using the returned result at all. – NathanOliver Mar 24 '23 at 17:51
  • `damage(playerHealth, spellFireDamage);` returns the new health but you threw the value calculated in the damage function away and thankfully your compiler tells you about that mistake. Did you want `playerHealth = damage(playerHealth, spellFireDamage);` – drescherjm Mar 24 '23 at 18:02
  • Related: [https://stackoverflow.com/questions/35679436/c-passing-by-reference-or-by-value](https://stackoverflow.com/questions/35679436/c-passing-by-reference-or-by-value) – drescherjm Mar 24 '23 at 19:17

1 Answers1

0

I'm guessing that you want:

void damage(int &health, int spellsDamage) {
    health -= spellsDamage * 3 + 5;
}

i.e. the two-parameter version of the function should reduce health by spellsDamage * 3 + 5. health is passed by reference so that the function can modify the caller's variable.

But I wouldn't have two such similar functions, especially with the same name. Just make up your mind what you want the function to do and stick with it.

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48