I am trying out operator overloading and I can't figure out why my program keeps crashing.
When I dereference p.name in the operator<< function it crashes, and when I don't refenece it, it just prints out an address of the string and the program does not crash. The core of the problem might be in setting object p1 equal to the return of the operator+ function, but I cant figure out what exactly happens there.
main.cpp
int main()
{
Player p1("John", 10);
Player p2("Jon");
cout<<p1<<endl;
cout<<p2<<endl;
p1=p2+20;
cout<<p1;
}
player.h
class Player
{
public:
Player(string _name);
Player(string _name, int _score);
~Player();
friend ostream& operator<<(ostream& os, Player& p);
Player operator+(int p);
private:
string *_name;
int _score;
};
player.cpp
Player::Player(string name)
{
_name=new string;
*_name = name;
_score = 0;
}
Player::Player(string name, int score)
{
_name=new string;
*_name = name;
_score = score;
cout<<"Konst1"<<endl;
}
Player::~Player()
{
delete _name;
_name = 0;
}
ostream& operator<<(ostream& os, Player& p)
{
os<<*p._name<<" won: "<<p._score<<" pts";
return os;
}
Player Player::operator+(int p)
{
Player obj(*_name, _score+p);
return obj;
}
Expected result would be "John won: 20 pts".
Edit: Putting string _name on heap memory is the part of the task I was given, so I have to try to make it work like that.