C++ friend function can't access public function of the class : <p>This is an excerpt of an implementation of a Stack class in C++:<br>
<strong>Stackdemo.hpp</strong></p>

<pre><code>#include&lt;iostream&gt;

using namespace std;

template&lt;typename T&gt;
class Stack
{
    private:
        int top;
        T *arr;

    public:
        Stack(int size)
        {
            arr = new T[size];
            top = 0;
        }

        void push(const T &amp;x)
        {
            arr[top++] = x;
        }

        int size()
        {
            return top;
        }

        friend ostream&amp; operator&lt;&lt;(ostream &amp;out, const Stack &amp;s)
        {
            for(int i = 0; i &lt; s.top; ++i) out&lt;&lt;s.arr[i]&lt;&lt;' '; // Works
            for(int i = 0; i &lt; s.size(); ++i) out&lt;&lt;s.arr[i]&lt;&lt;' '; // Doesn't work

            return out;
        }
};
</code></pre>

<p>Here I am using a simple driver program to test it:<br>
<strong>StackTest.cpp</strong></p>

<pre><code>#include&lt;iostream&gt;
#include"Stackdemo.hpp"

int main()
{
    Stack&lt;int&gt; S(5);

    S.push(1);
    S.push(2);
    S.push(3);

    cout&lt;&lt;S&lt;&lt;'\n';

    return 0;
}
</code></pre>

<p>My problem is in the operator overloading function: the first loop works and produces the expected output, but the second doesn't and gives an error "passing 'const Stack' as 'this' argument discards qualifiers [-fpermissive]". Obviously, I'd be using only one loop at a time. Why is there an issue, since size() just returns the value of top?</p>
