1

I have two classes in my code: CoinManager, which has one function only, which is to add a specific amount of coins to a specific Player object, and the Player class.

class Player{
public:
    void addCoins(int amount){
        coins+=amount;
    }
    int getCoins(){
        return coins;
    }
private:
    int coins = 0;
}
class CoinManager{
public:
    void freeCoins(Player user, int amount){
        user.addCoins(amount);
    }
}
int main(){
    Player i;
    CoinManager CM;
    i.addCoins(20); //this works
    CM.freeCoins(i, 20); //this doesn't work
}

With the CoinManager class I can have a getter function of Player's coins like this:

int getCoins(Player user){
    return user.getCoins();
}

But I cannot use the freeCoins(Player i, int amount); function. No error comes up, simply the function does not change the value of coins in the Player object.

  • 3
    You're passing a copy of `i` to the `freeCoins` method. You'll need to pass a pointer or reference. – Cornstalks Mar 13 '16 at 21:03
  • Ah, alright. Could you link me to some pointer article? I'm only a beginner in C++. – user5749558 Mar 13 '16 at 21:06
  • @user5749558 You can read the C++ tag wiki here, which links many useful things. http://stackoverflow.com/tags/c%2b%2b/info – Zan Lynx Mar 13 '16 at 21:07
  • 1
    Also, dull as it sounds, check google. This is a VERY common stumbling point for new programmers, and there are bazillion articles out there covering the subject. There's sure to be at least one that makes it "click" for you. – Vilx- Mar 13 '16 at 21:08
  • 1
    `void freeCoins(Player &user, int amount)` – M.M Mar 13 '16 at 21:09
  • Thank you, how can I close this question? – user5749558 Mar 13 '16 at 21:09
  • OP, the best way for this question to be closed would be for @Cornstalks to post his comment as answer so you can accept it and future readers can still learn from this question. (Rather than this question just being permanently deleted, which offers no help to future readers.) – Spencer D Mar 13 '16 at 21:11
  • For me, I like to think of pointers this way: every byte in memory has an "address" or ordering number. There's the first byte, the second byte, etc. Every variable you make, resides in some bytes out there. A "pointer" is just another variable (so it too takes up a few bytes of memory) which itself contains the address number for some byte in memory. If you know what data resides in that memory (for example, it's the first byte of an integer), then you can manipulate that data like another variable. – Vilx- Mar 13 '16 at 21:12
  • In C/C++, you can have a pointer to the first byte of anything you can store in a regular variable (yes, you can have a pointer to a pointer as well, just for kicks :) – Vilx- Mar 13 '16 at 21:12

0 Answers0