#include <iostream>
using namespace std;
class Player
{protected:
int health;
int mana;
public:
Player :: Player()
{
health = 0;
mana = 0;
}
Player :: Player(int Health, int Mana)
{
health = Health;
mana = Mana;
}
int GetHealth()
{
return health;
}
int GetMana()
{
return mana;
}
void SetHealth(int Health)
{
health = Health;
}
void SetMana(int Mana)
{
mana = Mana;
}
~Player()
{}
};
int main()
{
Player *player1 = new Player();
Player player2(10,20);
cout << player1 -> GetHealth() << "\n" << player2.GetHealth();
return 0;
}
Alright, I'm trying to familiarize myself with the class system within C++ and I'm running into an odd problem.
The above code gets me the health of player1 and player2, however, this was after a bit of researching as my first attempt attempted to get player1's health by doing
...
Player player1();
Player player2(10,20);
cout << player1.GetHealth()<< "\n" << player2.GetHealth();
...
The above snippet won't compile as it says player1 needs to declare a class, but if removed player2's health works fine.
My questions are:
1. why does the void constructor not work when initialized this way, but the overloaded constructor does?
2. When a pointer is declared
Player *player1 = new Player();
where is it pointing to? Does it create a memory address not attached to a variable where Player() is initialized?
Think I'm not understanding new as you can't declare
Player player1 = new Player();
as new Player() is a pointer type.
3. What exactly is ->? I noticed it was used in some code when calling functions tied to a variable whose class needs internal functions to be called. However, exactly what it is I wasn't entirely sure of. Google didn't bring up too much meaningful info on it.