Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling function to return private variable from class not working

Tags:

c++

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.

like image 229
CMP6LG Avatar asked Feb 19 '23 21:02

CMP6LG


1 Answers

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;
like image 125
Geoff Montee Avatar answered Feb 21 '23 09:02

Geoff Montee