0

I'm just practicing creating a stack class and I'm trying to overload operator= and operator+. So far I have successfully overloaded the operator=.

Let's say my objective is to be able to do st3 = st1 + st2; operation in the main where st1, st2, st3 are the objects of class stack and assuming they all have the same size and are all int values.

Right now st3 is not returning any values.

In my class I had:

 stack& operator+(stack& otherStack){
        int sum = 0;
        stack res;
        while ((!this->isEmpty()) && (!otherStack.isEmpty())) {
            sum = this->top() + otherStack.top();
            res.push(sum);
            this->pop();
            otherStack.pop();
        }
        return res;
    }

And here is my print() function using recursion which is also in class stack. It prints st1 and st2 just fine

void printStack(){
        if (isEmpty())
            return;
        int x = this->top();
        this->pop();
        this->printStack();
        this->push(x);
    }
  • What is your question? I didn't get what is wrong about the code. Overall it seems like a bad idea (operator+) is not really relevant. Swap would be a better candidate. Transforming operations are done using `std::transform` which needs either iterators or views (C++20). – Incomputable Nov 24 '21 at 09:40
  • Do you *really* want the addition of two stacks to empty the stacks? It's a very surprising behaviour. (And printing is simpler to do with a copy, rather than your "modify, recurse, and restore" approach.) – molbdnilo Nov 24 '21 at 09:53
  • Well I didn't really have any other way to iterate through the stacks without popping off the top. Again, I'm just testing out all that I can do. – Jim_Jimmadome Nov 24 '21 at 09:55

1 Answers1

0
stack& operator+(stack& otherStack){
    stack res;
    ...
    return res;
}

res is an automatic variable. Its lifetime ends when it goes out of scope; i.e. when the function returns. You return a reference to this object whose lifetime has ended. The returned reference is always dangling, and attempting to access the object will result in undefined behaviour.

Solution: Return an object; not a reference.


Operator+ that modifies the operands is unconventional, and I highly recommend against such design.

eerorika
  • 232,697
  • 12
  • 197
  • 326