I have implemented a simple templated class for a stack using linked list as such:
template <typename T>
struct Element
{
T data;
Element<T> *next;
};
template <typename T>
class Stack
{
private:
Element<T> *m_top;
public:
Stack(); // create an empty stack
void push(T value);
T pop();
T top();
bool isEmpty();
};
In the implementation of the top() which returns the value stored in the element at the top of the stack without removing it, I am getting the following error:
warning: control reaches end of non-void function [-Wreturn-type]
I have enabled -std=c++1 -pedantic -Wall options with g++. Here's the top():
template <typename T>
T Stack<T>::top()
{
if (this->isEmpty()) // isEmpty() returns true if m_top == nullptr, false otherwise
{
std::cerr << "Stack empty!" << std::endl;
}
else
{
return m_top->data;
}
}
Since there are only two possible values- either the stack is empty or not, therefore the if-else construct. But what do I put inside the if clause after the std::cerr statement to make the compiler happy and not get the warning? I cannot simply put a return; statement as the compiler expects a value to be returned. Also if the stack is empty, there is nothing to be returned.
Additional help:
Is it a good practice to leave the compiler complaining when you know the logic of the program is right?
Aucun commentaire:
Enregistrer un commentaire