Search code examples
c++encapsulationmember-functionsmutability

Member functions change object from main but not from other function


I have a Stack class which uses a linked-list class list internally. In my main function, my push and pop member functions successfully modify the given stack. I have written another function that takes a stack and performs some operations on it. Internally it uses push and pop. The weird thing is that the appears to change inside this function, but after it executes the stack remains unchanged. I'll provide some of the code (I can add more if necessary):

void run_stack_op(Stack stack, string token) {
    int operand1 = stack.pop();
    int operand2 = stack.pop();
    intfunc f = fmap[token];
    cout << operand1 << ", " << operand2 << ", " << f(operand2, operand1) << endl;
    stack.push(f(operand2, operand1));
    cout << "current stack (in run_stack_op): " << stack.to_string() << endl;
}

...then in main:

s = Stack();
s.push(3); s.push(4);
run_stack_op(s, "-");
cout << "current stack (in main): " << s.to_string() << endl;
int val = s.pop();
cout << "should be -1: " << val << endl;

which results in:

4, 3, -1
current stack (in run_stack_op): -1 
current stack (in main): 4 3 
should be -1: 4

Solution

  • Try using reference instead of copying the object.
    Add & after the type to use reference.

    void run_stack_op(Stack& stack, string token) {