Class variable not reachable from class method

I am trying to implement a circular queue.

I have declared size of the queue in the header file and I initiated my queue using size variable via constructor.

Here are queue.h and queue.cpp files.

class Queue
{
   public:
   int size;
   int front, rear;
   int A[];

   Queue(int size);
   bool isEmpty();
   void enqueue(int n);
   int dequeue();
   int Peek();
   void Display();
   int sizeQ();
};

Here is queue.cpp

Queue::Queue(int size)
{
   int A[size];
   front = rear = -1;
}

bool Queue::isEmpty(){
if((front == -1)  && (rear == -1))
    return true;
else
    return false;
}


void Queue::Display(){
if(isEmpty()){
    cout << "Its empty! Nothing to display"<<endl;
}else{
    for(int i=0; i<sizeQ(); i++){
        cout << A[i] << endl;
    }
}
    cout <<endl;
}

Here is my main

int main()
{

   Queue q1(10);
   q1.enqueue(20);
   q1.Display();
   return 0;
}

The problem: Loop inside display function does not see the size variable although I created object using size inside main. When I debug the program, I saw that size is 0, thus for loop never starts.

What I tried

 int Queue::sizeQ(){
   return size;
}

I tried to return size via method; however, no luck. What should I do in order to access size variable?

3 answers

  • answered 2019-10-14 04:24 Gaurav Sehgal

    Queue::Queue(int size)
    {
       int A[size];
       front = rear = -1;
    }
    

    You never initialize this->size here. Hence sizeQ() returns uninitialized value of size member.

    Add this->size = size; inside the constructor.

    EDIT: the int A[size] does not do what you think it does. It is creating a local array and has nothing to do with the member A. Refer to @jignatius answer to see how to fix it.

  • answered 2019-10-14 04:40 Sadashiva SM

    Initiate size inside constructor like below:

    Queue::Queue(int nSize) //changed name of parameter to nSize to remove confusion
    {
       int A[size];
       front = rear = -1;
       size = nSize; // Initialize passed param to member variable of class
    }   
    

  • answered 2019-10-14 04:54 jignatius

    Currently your constructor creates a local array that gets destroyed after it completes. You don't want to do this.

    If you want to set the size of an array at run time it has to be declared on the heap. To do that you should change the declaration of the array A like this in the header:

    int *A;
    

    Then in your constructor you can allocate the array on the heap:

    Queue::Queue(int iSize): 
        size(iSize), front(-1), rear(-1)
    {
       A = new int[size];
    }
    

    Note the initialiser list is initialising member variables size, front and rear.

    You must also deallocate your array. To do this add a destructor to your class Queue and do this:

    Queue::~Queue()
    {
       delete [] A;
    }
    

    This will free up the memory used by A.