I've been learning C++ and I am practicing with classes at the moment. I created a class that stores a name and a score of a player and defines functions to manipulate the data and show it.
One of the functions I created is to compare scores of two players and return a pointer to the player with the higher score. This is the function:
Player * Player::highestScore(Player p2)const
{
if(p2.pScore>pScore)
{
return &p2;
}
else
{
return this;
}
}
From the main I create the following players:
Player p1("James Gosling",11);
Player *p4 = new Player("Bjarne Stroustrup",5);
I call the highestScore function:
Player *highestScore = p1.highestScore(*p4);
However as you may have noticed from reading the function itself, when I return the pointer to the object that called the method (if it has a higher score), I get an error that says:
return value type does not match the function type
This problem seems to disappear when I declare the return type of the function as a const
, like this:
const Player * Player::highestScore(Player p2)const
The part that is confusing me is why does it allow me to return &p2
, which is not const
and doesn't allow me to return this
, which is a pointer to the object that called the function, which isn't a const
as well? Also even when I declare the function return type as a const, it still allows me to return &p2
, even though the argument passed to the parameter is not a const Player object?
Sorry if the question seems strange or what I'm trying to do is very bad programming, but it's just for the purpose of learning by doing it.