Search code examples
c++classdynamic-memory-allocation

Unable to access variable of same class from other functions inside the class


I am unable to access my 'arr' variable from other push and pop functions inside the class. Getting the error " 'arr' was not declared in this scope". It should be accessible inside the class. I could just allocate memory statically as a solution, but I wanted to try this.

The program gives reverse polish notation.
input
1
(a+b)
o/p
ab+

#include <iostream>
#include <string>
using namespace std;


class stackOperations{
  private:
    int top = -1 ;
  public:
  void allocate(int len){
    char *arr = new char[len] ;
  }
  void deallocate(){
    delete []arr ;
  }
  void push(char x){
      top++;
      arr[top] = x ;
  }
  char pop()
  {
      char temp;
      temp = arr[top];
      top--;
      return temp;
  }
};

void RPN(string exp)
{
    stackOperations st ;
    int len = exp.length();
    st.allocate(len);
    for(int i=0; i <=len; i++){
        char tmp ;
        tmp = exp[i];
        if(tmp=='('){
            st.push('(');
        }
        else if(tmp==')'){
            char y = st.pop();
            while(y != '('){
                cout << y ;
                y = st.pop();
                }
            }
        else if(int(tmp) >= 97 && int(tmp) <= 122 ) {
            cout << tmp ;   
        }
        else {
            st.push(tmp);
        }

    }
    st.deallocate();
}

int main() {
    int test ;
    string exp ;
    cin >> test;
    cin.ignore();
    while(test!=0){
        getline(cin, exp);
        RPN(exp);
        cout << endl ;
        test--;
    }
    return 0;
}

Solution

  • class stackOperations{
        private:
              int top = -1 ;
              char *arr;
         public:
          void allocate(int len){
               arr = new char[len] ;
      }