Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: request for member '..' in 'this', which is of non-class type '--* const'

Tags:

c++

My first ever question here. Please excuse me, I have just entered into C++ and was starting up with DS. STACK!!!

My code: I think

    using namespace std;
    typedef char stackElement;

    class Stack
    {
    public:
        stackElement *contents;   //dynamically allocated: as we do not know what would be the size of our array.
        int top, maxSize;               // current Top index in the array

                //max size of the array; we need it to know if the array is full

    Stack(int maxSize)
    {

        contents = new stackElement(maxSize);
        this.maxSize = maxSize;
        if(contents == NULL)
        {
            cout<<"Insufficient memory";
            exit(1);

        }

        top = -1;
    }
    ~Stack()
    {
        delete [] contents;
        contents = NULL;
        maxSize = 0;
        top = -1;

    }

    bool isEmpty()const
    {

        return top < 0;
    }
    bool isFull() const
    {

        return top == maxSize - 1;
    }


    void push(stackElement element)
    {
        if(isFull())
        {
            cout<<"STACK IS ALREADY FULL";
            exit(1);
        }
        top = top + 1;
        contents[top] = element;
    }


};

int main()
{

    cout<<"STACK IMPLEMENTATION";
    int i = 1;
    Stack s1(i);


    s1.push('a');
    s1.push('1');
    return 0;
}

I am getting this error:

error: request for member 'maxSize' in 'this', which is of non-class type 'Stack* const'
like image 901
Roger Avatar asked Dec 07 '22 17:12

Roger


2 Answers

If at all, you'd have to write this->maxSize = maxSize;, since this is a pointer.

But better not to write that at all and instead use the constructor-initializer list:

  explicit Stack(int m)
  : contents(new stackElement[m]), top(-1), maxSize(m)
  {
      // nothing else to do
  }

I also added explicit so you don't accidentally convert 5 into a Stack.

You also wrote the array initialization wrong.

Also, you don't need to check that contents is not null: When new fails, it exits with an exception, it does not return a null pointer. (That behaviour would make no sense when you think in terms of objects.)

It is crucial to note that you have at most one naked new-expression in your constructor. Anything else is an exception-safety disaster, and a sign that you need to refactor and use single-responsibility resource-managing classes.


The destructor should just be: ~Stack() { delete [] contents; } Everything else is pointless waste.


Imagine you had to pay for every line of code you write. Be patient, lose the source, think.

like image 153
Kerrek SB Avatar answered Dec 09 '22 07:12

Kerrek SB


Write

 this->maxSize = maxSize;

instead of

 this.maxSize = maxSize;

The this is a pointer type, not a reference type

like image 25
Nawaz Avatar answered Dec 09 '22 06:12

Nawaz