CMP6LG
CMP6LG

Reputation: 83

Calling function to return private variable from class not working

So I am making a small game in C++ and I have run across a problem. I have a class called player inside my player.h file, and inside this class I have a public function called getPotion(). I also have a private static variable called potion. I have the exact same thing for the players health, and the getHealth() function returns the private static int playerHealth perfectly. But for apparently no reason, the getPotion function doesn't return the potion. I get an error instead. I've also included the header file in all my other files.

Here's the code:

(Sorry, I don't know how to insert code, so I have to write it out)

player.h (the code that I'm having trouble with):

class Player{
private:
    static int potions;

public:
    int getPotions();
}

player.cpp (again the code I have trouble with):

int Player::potions;

int Player::getPotions(){
    Player player;
    return player.potions;
}

I have probably left out some bits of code like return and such, but that's because I have a small amount of time to ask this question, so I put the parts that related to my problem.

Upvotes: 4

Views: 14774

Answers (2)

Geoff Montee
Geoff Montee

Reputation: 2597

First off, you are trying to return a static member of a class as if it were instantiated member of the object. Static members are referred to by Class::member, not object.member.

Second, I don't think you want potions to be static. Static members are shared between all objects of the class. So if player A has 100 health potions, then player B would have the same 100 health potions.

Third, you declare Player::potions at the top of your .cpp file. I don't think that's what you want. The potions member was already declared in your .h file.

player.h:

class Player
{
    private:
        int potions;

    public:
        int getPotions();
};

player.cpp:

int Player::getPotions()
{
    return potions;
}

If you DID want potions to be static, then change it to:

return Player::potions;

Upvotes: 7

jedwards
jedwards

Reputation: 30260

Try changing

Player player;
return player.potions;

to simply

return potions;

You're creating a new player and returning that object's potions, not the potions of the "this" object.

Upvotes: 1

Related Questions