/*
Why does the following fail?
*/
#include <iostream.h>

class stack {
    protected:
	int count;
	int size;
	int *data;
    public:
	stack(const int i_size): count(0), size(i_size)
	{
	    data = new int[size];
	}
	virtual ~stack(void) {
	    delete []data;
	    data = NULL;
	}
	stack(const stack &new_stack) {
	    delete []data;
	    data = new int[new_stack.size];

	    int i;
	    for (i = 0; i < new_stack.count; ++i) {
		data[i] = new_stack.data[i];
	    }
	}
	stack & operator = (const stack &new_stack) {
	    delete []data;
	    data = new int[new_stack.size];

	    int i;
	    for (i = 0; i < new_stack.count; ++i) {
		data[i] = new_stack.data[i];
	    }
	    return (*this);
        }
    public:
	void push(const int item) {
	    data[count] = item;
	    ++count;
	}
	int pop(void) {
	    --count;
	    return (data[count]);
	}
};

void two_more_elements(
    stack &to_stack,
    const stack &from_stack
)
{
    to_stack = from_stack;
    to_stack.push(1);
    to_stack.push(3);
    to_stack.push(5);
}
int main()
{
    stack a_stack(30);

    a_stack.push(2);
    two_more_elements(a_stack, a_stack);
    return(0);
}

/* Tree surgone law: Don't cut off the limb you are standing on. */

/* This program tries to copy data just after it deletes it. */

/* What does a_stack.operator = (a_stack) do? */

/* The problem is that we have

   	a_stack = a_stack;

This is diguised as:

	to_stack = from_stack;

The "operator =" function deletes the data of the destination
stack.  That's fine, except that the source stack is the same
stack, so it's data gets destroyed too.

The answer is to explicitly check for self assignment
in the operator = function:

	stack & operator = (const stack &new_stack) {
	    if (this == &new_stack)
		return;

	    delete []data;
	    data = new int[new_stack.size];

	    int i;
	    for (i = 0; i < new_stack.count; ++i) {
		data[i] = new_stack.data[i];
	    }
	    return (*this);
        }

Avoidance: Opeator = should check for self assignment.
*/
