template<class T> class Stack_Template
{
T* v;
int top;
int max_size;
public:
// Exception/error handling
class Underflow{}; // Used as exception (class = type)
class Overflow{}; // Used as exception
class Bad_Size{}; // Used as exception
Stack_Template(int s); // Constructor
~Stack_Template(); // Destructor (used for cleanup when an object of the class goes out of scope)
void push(T);
T pop();
};
How do I create the constructor/destructor subroutines correctly?
Here's what I have so far but they do not work:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Constructor
template<class T> Stack_Template::Stack_Template(int s)
{
top = 0;
if (s < 0 || s > 10000)
{
throw Bad_Size();
}
max_size = s;
v = new T[s]; // allocate elements on the free store (heap, dynamic store)
}
// Destructor (Frees memory)
template<class T> Stack_Template::~Stack_Template()
{
delete[] v; // Free the elements for possible reuse of their space
}
#include <exception>
template<class T> class Stack_Template
{
T* v;
int top;
int max_size;
public:
// Exception/error handling
class Underflow : public std::exception{}; // Used as exception (class = type)
class Overflow : public std::exception{}; // Used as exception
class Bad_Size : public std::exception{}; // Used as exception
Stack_Template(int s); // Constructor
~Stack_Template(); // Destructor (used for cleanup when an object of the class goes out of scope)
void push(T);
T pop();
};
Typically you'll want to customize the error string returned by std::exception::what(),
and to do that you might consider providing a forwarding constructor for Underflow
(that takes the error message).