I'm fairly new to C++ programming. To help I've been writing my own data structures for practice. I'd liked this to be judged as if it was written by a professional, and receive honest feedback. I already have a few concerns.
Am I managing memory correctly? I don't believe I have any leaks. A lot of advice I get when using pointers is to use smart pointers, but raw pointers are fine when the class encapsulates all pointers correct?
I'm unhappy my
<<
operator overload has to call topeekAll
inside the class. I feel like I'm going about this in the wrong way. Aside from that should I overload any other operators? I didn't feel arithmetic operators made much sense.
#include <ostream>
template <typename T>
class BBStack {
public:
BBStack(T type) {
head = new Node(type);
}
virtual ~ BBStack() {
Node* temp = head;
while (head != nullptr) {
temp = head->next;
delete head;
head = temp;
}
delete temp;
}
void push(T type) {
Node *newNode = new Node(type, head);
head = newNode;
}
T peek() const {
return head->data;
}
T pop() {
if (head == nullptr) {
std::cout<<"Error stack is empty"<<std::endl;
return NULL;
} else {
Node *temp = head;
T result = temp->data;
head = head->next;
delete temp;
return result;
}
}
std::ostream& peekAll(std::ostream& out) const {
if (head == nullptr) return out << "Stack is empty";
Node* temp = head;
while (temp != nullptr) {
out << temp->data << " ";
temp = temp->next;
}
delete temp;
return out;
}
private:
struct Node {
Node(T type, Node* _next = nullptr) : data(type), next(_next) {}
Node(Node* node) : data (node->data), next (node->next) {}
T data;
Node* next;
};
Node* head;
};
template <typename T>
std::ostream& operator<< (std::ostream& out, const BBStack<T>& stack) {
return stack.peekAll(out);
}