I am facing a very specific problem when trying to implement a generic queue in C++. Here is the code:
template <class T> class Queue {
private:
T * queue;
int front;
int back;
int MAX_SIZE;
public:
Queue(){
Queue(SOME_PREDEFINED_CONSTANT);
}
Queue(int size){
queue = new T[size];
MAX_SIZE = size;
front = 0;
back = 0;
cout << "inside constructor:" << " back= " << back << " front=" << front << endl;
}
void push(const T entry){
if(back < MAX_SIZE){
queue[back] = entry;
back++;
}
}
T peek(){
return queue[front];
}
void pop(){
if(size() > 0){
front++;
}
if(front==back){
front = 0;
back = 0;
}
}
int size(){
cout << "size:" << " back=" << back << " front=" << front << endl;
return (back-front);
}
};
When I am initializing the queue, like this: Queue <int> q;
, I get the correct values of back
and front
inside the constructor; The output:
inside constructor: back=0 front=0
But when I am asking for the size of the queue, like this: q.size()
(without any push/pop operation), I get very weird values of back
and front
. One sample output:
size: back=32766 front=-746749592
Can anyone please point out what I am doing wrong here?