Handout 24c
A Small Inheritance Example*
// Original code by Dr. T.K. Prasad; modified by Venu Dasigi
// example of an integer stack
#include <iostream.h>
class stack {
protected: // cannot be PRIVATE for subclassing
int s[100]; // sufficiently large
int top;
public:
stack(void) { top = -1; }
void push(int c) { s[++top] = c; }
int pop(void) { return (s[top--]); }
bool empty(void) { return (top == -1); }
};
class bounded_stack : public stack {
private:
int limit; // number of elements = limit+1
public:
bounded_stack(int size) : stack() {limit = size - 1;}
void push(int c) { if (top < limit) stack::push(c);
else cout << " ERROR: Stack Bound Exceeded" << endl;}
bool full(void) { return (top == limit); }
};
void main(void) {
int i, n;
stack st;
bounded_stack bst (3); // one less than the number of elements pushed
cout << endl;
cout << " Input four (blank separated) integers: ";
for(i=0;i<4;i++) {
cin >> n;
st.push(n);
bst.push(n);
}
cout << endl
<< " Integer List in Reverse (Stack):";
while (! st.empty()) {
cout << st.pop() << " ";
}
cout << endl
<< " Integer List in Reverse (Bounded Stack):";
while (! bst.empty()) {
cout << bst.pop() << " ";
}
cout << endl << endl;
}
// EXPECTED OUTPUT
/*
Input four (blank separated) integers: 22 33 44 55555
ERROR: Stack Bound Exceeded
Integer List in Reverse (Stack):55555 44 33 22
Integer List in Reverse (Bounded Stack):44 33 22
*/
* from here. Source code.