c++stackautomatic-storage

Why does this automatic-storage structure still exist?


Code

stack.h:

struct customer
{
    char fullname[35];
    double payment;
};

typedef customer Item;

class Stack
{
private:
    ...
    Item items[MAX];
public:
    ...
    bool push(const Item & item);
    bool pop(Item & item);
};

main.cpp:

#include "stack.h"

...

int main()
{
    Stack s; double total;
    while (1)
    {
        ...
        cin >> c;
        switch (c)
        {
        case '1': push(s);
            break;
        case '2': pop(s, total);
            break;
        ...
        }
    }
    ...
}

void push(Stack & s)
{
    Item newitem;
    cout << "name -- ";    cin >> newitem.fullname;
    cout << "payment -- "; cin >> newitem.payment;
    s.push(newitem);
}

void pop(Stack & s, double & total)
{
    Item olditem;
    s.pop(olditem);
    total += olditem.payment;
}

Remark

Most of main() is probably irrelevant, but I just want to show what I'm doing. push() and pop() are the important blocks.

The code above is supposed to fill a stack with Items. When an Item is popped, its payment is added to a running total.

Also, differentiate between Stack methods pop() and push() with the functions in main().


Dilemma

The code works exactly as I want it to, but I don't understand why...

I create a local Item in the push() function. It is referenced and placed onto the Stack. However, when the push() function ends, shouldn't this local Item be removed since it is on automatic storage? Yet, somehow it still exists because when I call pop(), there it is.


Solution

  • The expression items[top] = item uses the copy assignment operator to copy the structure.