#include <vector>
class iStack {
public:
iStack( int capacity )
: _stack( capacity ), _top( 0 ) { }
bool pop( int &top_value );
bool push( int value );
bool full();
bool empty();
void display();
int size();
private:
int _top;
vector< int > _stack;
};
// stackExcp.h:
// stackExcp.h
class popOnEmpty { /* ... */ };
class pushOnFull { /* ... */ };
pop() must throw an object of class type. The expression in the throw expression cannot simply be a type. To create an object of class type, we need to call the class constructor.iStack’s pop() and push() member functions:
#include "stackExcp.h"
void iStack::pop( int &top_value )
{
if ( empty() )
throw popOnEmpty();
top_value = _stack[ --_top ];
cout « "iStack::pop(): " « top_value « endl;
}
void iStack::push( int value )
{
cout « "iStack::push( " « value « " )\n";
if ( full() )
throw pushOnFull();
_stack[ _top++ ] = value;
}
Because exceptions are now used to indicate the failure of the pop() and push() operations, the return values from these functions are now unnecessary.