I started programming in Cpp few days back so I am still getting familiar with concept of pointer. I know programming style and logic is crude.
#include <iostream>
using namespace std;
class node
{
public:
int data;
node *next;
node()
{
data = 0;
next = nullptr;
}
};
class Stack
{
private:
node *top;
node *first;
public:
Stack();
void push();
void display();
};
Stack::Stack()
{
top = new node();
}
void Stack::push()
{
int data;
cout<<"Enter data: ";
cin>>data;
node *n = new node();
n->data = data;
if(top->next == nullptr)
{
top->next = n;
}
else
{
node *temp = new node();
temp = top;
while(temp->next != nullptr)
{
cout<<"while here!"<<endl;
temp = temp->next;
}
temp->next = n;
}
}
void Stack::display()
{
node *temp;
temp = top;
while(!(temp->next == nullptr))
{
cout<<temp->next->data<<" ";
temp = temp->next;
}
}
int main()
{
int n, ch;
bool isTrue = true;
Stack *s = new Stack();
//Stack s();
cout<<"1.Push\n2.Display\n3.Exit"<<endl;
while (isTrue)
{
cout<<"Enter Your Choice: ";
cin>>ch;
switch (ch)
{
case 1:
//s.push(); //Editor was pointing here
s->push();
break;
case 2:
//s.display(); //Editor was pointing here
s->display();
break;
case 3:
isTrue = false;
break;
default:
cout<<"Wrong Choice!"<<endl;
break;
}
}
}
when i created object s
of class Stack
in stack memory I was unable to call any function. s.display
and s.push
is where editor is pointing and saying Expression must have a class type. I searched about it a lot and couldn't find a solution. So, I created object s
of class Stack
in heap memory (I don't know why maybe I had a gut feeling that it might work) and it actually worked but I still unable to understand why.
May you explain why?