Returning "this" pointer in a const function
<p>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.</p>

<p>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:</p>

<pre><code>Player * Player::highestScore(Player  p2)const
{
    if(p2.pScore&gt;pScore)
    {
        return &amp;p2;
    }
    else
    {
        return this;
    }
}
</code></pre>

<p>From the main I create the following players:</p>

<pre><code>Player p1("James Gosling",11);
Player *p4 = new Player("Bjarne Stroustrup",5);
</code></pre>

<p>I call the highestScore function:</p>

<pre><code>Player *highestScore = p1.highestScore(*p4);
</code></pre>

<p>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:</p>

<pre><code>return value type does not match the function type
</code></pre>

<p>This problem seems to disappear when I declare the return type of the function as a <code>const</code>, like this:</p>

<pre><code>const Player * Player::highestScore(Player  p2)const
</code></pre>

<p>The part that is confusing me is why does it allow me to <code>return &amp;p2</code>, which is not <code>const</code> and doesn't allow me to return <code>this</code>, which is a pointer to the object that called the function, which isn't a <code>const</code> as well? Also even when I declare the function return type as a const, it still allows me to <code>return &amp;p2</code>, even though the argument passed to the parameter is not a const Player object?</p>

<p>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.</p>
