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?