Search code examples
c++operator-overloadingfriend

C++ friend function can't access public function of the class


This is an excerpt of an implementation of a Stack class in C++:
Stackdemo.hpp

#include<iostream>

using namespace std;

template<typename T>
class Stack
{
    private:
        int top;
        T *arr;

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

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

        int size()
        {
            return top;
        }

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

            return out;
        }
};

Here I am using a simple driver program to test it:
StackTest.cpp

#include<iostream>
#include"Stackdemo.hpp"

int main()
{
    Stack<int> S(5);

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

    cout<<S<<'\n';

    return 0;
}

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?


Solution

  • Your size() is non-const and because of this you cannot call it on a const Stack &s. As the method does actually not modify any members it should be declared as const anyhow :

    int size() const {
        return top;
    }
    

    As a rule of thumb you can declare every member method as const and only if it needs to modify members remove the const.