My question is related to templates, below is the program that implements a generic stack class. I am required to create a stack object and push elements to there. I am using boolean push function(I am required to,in order to learn)
When called it must print a message "Inserted" and return true(1) or false(0). It is printing the message but not displaying 1 or 0 when called. If you could help me figuring out the error, I would be very thankful!
#include <cassert>
#include <iostream>
usingnamespace std;
template<class T, int initialsize = 10>
class Stack
{
T *ptr; // data will be stored in an array
int size; // number of elements in the array
int where; // last non-free position
public:
Stack();
Stack(const Stack&smth);
Stack(int newsize);
~Stack();
bool push(const T& element); // inserts an element
};
template<class T, int initialsize>
Stack<T, initialsize>::Stack()
{
ptr = new T[10]; // creates a vector of the given size
size = initialsize;
where = -1; // no elements up to now
}
//copy constructor
template<class T, int initialsize>
Stack<T, initialsize>::Stack(const Stack&smth)
{
ptr = new T[10]; // creates a vector of the given size
*ptr=*smth;
size = initialsize;
where = -1; // no elements up to now
}
//constructor with specified size
template<class T, int initialsize>
Stack<T, initialsize>::Stack(int newsize)
{
ptr = new T[newsize]; // creates a vector of the given size
size = newsize;
where = -1; // no elements up to now
}
//destructor
template<class T, int initialsize>
Stack<T, initialsize>::~Stack()
{
cout<<"Deleting"<<endl;//message
delete[] ptr; // deallocate memory
}
template<class T, int initialsize>
bool Stack<T, initialsize>::push(const T& element)
{
if (where + 1 == size)
returnfalse;
else {
where++; // and insert the element
ptr[where]=element;
cout<<"Inserted"<<endl;
returntrue;
}
}
the following is cpp file with main function:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include "Stack.h"
usingnamespace std;
int main(int argc, char** argv)
{
Stack<int> intstack; // stack with the default size
Stack<float, 1000> floatstack; // stack with specified size
int i;
int j;
for (i = 2; i < 20; i++)
intstack.push(i);
}