The following is a class template that implements a stack using an array:
#include <iostream>
using namespace std;
template <typename T>
class stack {
public:
stack (int priv_size) {
T a[priv_size];
top = 0;
}
stack (const stack &s) {
T b[priv_size];
for (top=0; top<s.priv_size; top++) {
b[top] = s.a[top];
}
top++;
}
~stack () {}
const stack& operator = (const stack &s) {
T b[s.priv_size];
for (top=0; top<s.priv_size; top++) {
b[top] = s.a[top];
}
top++;
}
bool empty () {
return top == 0;
}
void push (const T &x) {
a[top++] = x;
}
T pop () {
T c = a[--top];
return c;
}
int size () {
return priv_size;
}
friend ostream& operator << (ostream &out, const stack &s) {
int i;
out << "[";
for (i=0; i<s.top-1; i++) {
out << s.a[i] << ", ";
}
if (i == s.top-1) out << s.a[s.top-1];
out << "]";
return out;
}
private:
int priv_size;
int top;
T a[];
};
int main () {
stack<int> s(10);
cout << "stack s is empty: " << s << endl;
s.push(42);
s.push(17);
cout << "stack s has 2 elements: " << s << endl;
cout << "Removing " << s.pop() << " from the stack..." << endl;
return 0;
}
However as i was trying out the different methods of the class in main
I realized that although priv_size
is initialized to the value of 10 here: stack<int> s(10);
it loses its value right after the constuctor is called.
When i tried debugging in my IDE i realized that once the constructor stack (int priv_size)
is called it created another variable priv_size
that is initialized to the value of 10 instead of using the priv_size
member of the class. The previous can also be seen here:
class member priv_size memory address (image)
and here:
unwanted variable priv_size memory address (image)
where the two variables are stored in different memory slots.
Why are the two variables different and why is the one in the second image created in the first place?
I have also tried implementing the class methods outside of the class, like this:
stack<T>::stack (int priv_size) {
T a[priv_size];
top = 0;
}
but i get these two error messages:
Member declaration not found
Type 'T' could not be resolved
What is going on here?
Thanks in advance.
PS: I am aware there are a couple very similar questions posted already, but the answers to those do not seem to fit my problem as my issue seems to be in the class itself and not in main
or any other function.
Here are two links to some similar questions:
C++ Class members lose values assigned in a member function
Losing a data member of a base class after the constructor is called