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.
First off, you are trying to return a
staticmember of a class as if it were instantiated member of the object. Static members are referred to byClass::member, notobject.member.Second, I don’t think you want
potionsto 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::potionsat the top of your.cppfile. I don’t think that’s what you want. Thepotionsmember was already declared in your.hfile.player.h:
player.cpp:
If you DID want
potionsto be static, then change it to: