0

I'm trying to implement a stack using linked list in cpp. I'm using class to make the linked list but I'm getting the following error and I dont understand why

#include <bits/stdc++.h>
using namespace std;

class Stack{
    public:
    int top;
    Stack* next;
    Stack(int data){ //constructor
        top = data;
        next = NULL;
    }
    void push(Stack* &head, int data);
    int pop(Stack* &head);
    bool empty(Stack* &head);
};

void Stack::push(Stack* &head, int data){
    Stack* s = new Stack(data);
    s->next = head;
    head = s;
}

int pop(Stack* &head){
    int x = head->top;
    head = head->next;
    return x;
}

bool empty(Stack* &head){
    if(head == NULL)
        return true;
    return false;
}

int main() {
        class Stack* s = new Stack(1);
        s.push(2);
        s.push(3);
        cout << s.empty(s) << endl;
        cout << s.pop(s) << endl;
        cout << s.pop(s) << endl;
        cout << s.pop(s) << endl;
        cout << s.empty(s) << endl;
}

ERROR: request for member 'push' in 's', which is of pointer type 'Stack*' (maybe you meant to use '->' ?)

request for member 'empty' in 's', which is of pointer type 'Stack*' (maybe you meant to use '->' ?)

request for member 'pop' in 's', which is of pointer type 'Stack*' (maybe you meant to use '->' ?)

When I used -> instead of . it said undefined reference to Stack::empty(Stack*&) and undefined reference to Stack::pop(Stack*&)

EDIT: I used -> instead of . and added Stack:: to pop and empty function and it worked but the constructor isn't working

tommo
  • 7
  • 3
  • The first set of errors are typos that you've fixed. Why are you asking about them? They do not belong in a [mre]. The second issue (undefined reference) is a common dup, because you've defniied `pop` and `empty` as global functions (and not members, like `push` is). – 1201ProgramAlarm May 25 '20 at 16:03

3 Answers3

1

As the error message says, when you have a Stack*, you need to use ->, and not ., like this:

s->push(s, 42);
s->empty(s);
// etc

However, you probably don't need a Stack* here at all, and could just use a regular Stack object.

Also, your member functions that are defined outside the class, need to be qualified with the name of the class. So you need:

bool Stack::empty(Stack* &head){

instead of:

bool empty(Stack* &head){

like you have already done for the Stack::push method.

cigien
  • 57,834
  • 11
  • 73
  • 112
0

You 'accidentally' declared a pointer. Change your code like this

int main()
{
    Stack s(1);
    s.push(2);
    ...
john
  • 85,011
  • 4
  • 57
  • 81
0

Use -> whenever you are accessing data member of structure pointed by a Pointer. In your case, try using -> instead of . on s in the main function () So, either do

Stack s; 
s.push(1);

Or

Stack* s;
s->push(s,1);
Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32