1
votes

im working on a project for school and have this error but i cannot figure out out to fix it:

error: passing ‘const xArray’ as ‘this’ argument of ‘size_t xArray::PushBack(int)’ discards qualifiers [-fpermissive] a.PushBack(temp);

Here is the function that the error comes from:

    istream& operator>>(istream& in, const xArray& a)
    {
          int temp;
          in >> temp;
          a.PushBack(temp);

          return in;
    }

Here is my code for PushBack:

    size_t xArray::PushBack(int c)
    {

            if(len == arraySize)
            {
                     int* temp = new int[arraySize* 2];
                     size_t i;
                     for(i = 0; i < arraySize; i++)
                     {
                            temp[i] = data[i];
                     }
                     delete [] data;
                     data = temp;
                     data[len+1] = c;
                     len = len + 1;
            }
            else
            {
                  data[len + 1] = c;
                  len = len + 1;
            }
    }

Any help on how to fix or an explanation of this error would be appreciated Thanks in advance

1
It's const, therefore you can't modify it in any way, including by pushing stuff onto it.user253751
It's exactly what the compiler says. You call a non const member function on a const object. In generally the istream >> operator changes the second element and should be passed by reference but not as a const reference.Timothy Murphy

1 Answers

1
votes

For istream& operator>>(istream& in, const xArray& a), a is declared as const, and calling PushBack() on it will fail because xArray::PushBack() is a non-const member function.

You might change the parameter type of a to non-const reference, such as

istream& operator>>(istream& in, xArray& a)
{
    ...
}