I am learning C++ and I made a simple stack class using a (reversed) linked-list to test my knowledge.
Are there any problems with the following code, or any suggestions to improve it?
I want to make sure I am getting things correct in the beginning so I don't make the same mistakes again in the future - especially memory management and avoiding leaks.
One thing to point out is that I included the implementation in the header file... I wouldn't normally do this but apparently there are problems when implementing methods with templates in .cpp files.
#ifndef TEST_STACK_H
#define TEST_STACK_H
#include <stdexcept>
template <class T>
class stack {
struct node {
T data;
node* previous;
node(T data, node *previous) : data(data), previous(previous) {}
};
node* head = nullptr;
int size = 0;
int max = -1; // -1 so isFull() == false when default constructor used
public:
stack() = default;
stack(int max) {
if (max <= 0) throw std::out_of_range("stack size must be > 0");
this->max = max;
}
~stack() {
node* n = head;
while (n != nullptr) {
node* previous = n->previous;
delete n;
n = previous;
}
}
void push(const T &object) {
if (isFull()) throw std::overflow_error("cannot push to a full stack");
head = new node(object, head);
++size;
}
T pop() {
if (head == nullptr) throw std::underflow_error("cannot get item from empty stack");
T item = head->data;
head = head->previous;
--size;
delete head;
return item;
}
T peek() {
if (head == nullptr) throw std::underflow_error("cannot get item from empty stack");
return head->data;
}
int getSize() {
return size;
}
bool isFull() {
return size == max;
}
bool isEmpty() {
return head == nullptr;
}
};
#endif