I am a beginner in programming. And I found this stack code on geeks for geeks. I am confused that how the operation like pop() after push() knows that top has been upgraded. For example in this code after three push() operations top is now 2 (that is top=2). Next function pop() is called now. How does this function know that the final state of top is now 2. I am a little confused.
/* C++ program to implement basic stack operations */
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
class Stack {
  int top = -1;
public:
  int a[MAX]; // Maximum size of Stack
  bool push(int x);
  int pop();
  int peek();
  bool isEmpty();
};
bool Stack::push(int x) {
  if (top >= (MAX - 1)) {
    cout << "Stack Overflow";
    return false;
  } else {
    a[++top] = x;
    cout << x << " pushed into stack\n";
    return true;
  }
}
int Stack::pop() {
  if (top < 0) {
    cout << "Stack Underflow";
    return 0;
  } else {
    int x = a[top--];
    return x;
  }
}
int Stack::peek() {
  if (top < 0) {
    cout << "Stack is Empty";
    return 0;
  } else {
    int x = a[top];
    return x;
  }
}
bool Stack::isEmpty() { return (top < 0); }
// Driver program to test above functions
int main() {
  class Stack s;
  s.push(10);
  s.push(20);
  cout << s.peek();
  cout << s.pop() << " Popped from stack\n";
  cout << s.peek();
  return 0;
}
 
     
    