c++ - Stack push using external function -


i'm trying implement stacks using constructors in c++. i'm required use external function push element on stack, however, doesn't seem work properly. pushexternal function seems "enter" push function, doesn't increase ind value, therefore doesn't add new element onto stack (for example in code, pushxternals try push value onto same index, last 1 used s.push - ind==2). i'm not sure i'm doing wrong.

oh, i'm supposed modify class code - pushexternal , main have remain unchanged.

#include <iostream> using namespace std;  class stack {     public:     int ind;     int * arr;  stack() {     arr = new int[25];     ind = -1; } ~stack() {     delete [] arr; }  void push(int val) {     arr[++ind] = val;     cout << "added " << arr[ind] << " " << ind << endl; }  void top() {     cout << "last: " << arr[ind]; } };  void pushexternal(stack s, int a) {     s.push(a); }  int main() {     stack s;     s.push(0);     s.push(1);     s.push(2);     pushexternal(s, 3);     pushexternal(s, 4);     pushexternal(s, 5);     return 0; } 

results:

added 0 0 added 1 1 added 2 2 added 3 3 added 4 3 added 5 3 top: 2 

void pushexternal(stack s, int a) {     s.push(a); } 

receives stack parameter, means receives object copy of object.

you should operate on references, way not send copy of object manipulated, reference of object, original object manipulated.


Comments