------------------------------------------------------------------------------
MC logo
C++ Integer Stack ADT
[^] Code Examples
------------------------------------------------------------------------------
<<C Integer Stack Driver istack2.h C++ Integer Stack Implementation>>
#include <iostream>

using namespace std;

// Stack of integers.  This is the class definition.
class IntStack {
        // Node structure.
        struct node {
                int val;        // Data in this node.
                node *next;     // Next node.

                // Construct a newly-created node.
                node(int v, node *n) { val = v; next = n; }

                // Delete all the nodes.
                void killall() { 
                        if(next) next->killall();
                        delete this;
                }

                // Print all the nodes.
                void printall(ostream &strm) { 
                        strm << val << " ";
                        if(next) next->printall(strm);
                }
        } *head;

 public:
        // Nice new empty.
        IntStack() { head = 0; }

        // Make it go away.
        ~IntStack() { if(head != 0) head->killall(); }

        // Operations.
        bool empty() const { return head == 0; }
        void push(int i) { head = new node(i, head); }
        int pop();
        int top() const { return head->val; }

        // Print contents
        void print(ostream &) const;
};

// Overload << to allow printing of stacks with other objects.
inline ostream & operator<<(ostream &strm, const IntStack &s)
{
        s.print(strm);
        return strm;
}

Note that C++ structs are allowed to have methods as well. In fact, the only difference between a struct and a class in C++ is that structs have default public visibility.
<<C Integer Stack Driver C++ Integer Stack Implementation>>