For my compsci class, I am implementing a Stack template class, but have run into an odd error:
Stack.h: In member function ‘
const T Stack<T>::top() const[with T = int]’:Stack.cpp:10: error: passing ‘
const Stack<int>’ as ‘this’ argument of ‘void Stack<T>::checkElements()[with T = int]’ discards qualifiers
Stack<T>::top() looks like this:
const T top() const {
checkElements();
return (const T)(first_->data);
}
Stack<T>::checkElements() looks like this:
void checkElements() {
if (first_==NULL || size_==0)
throw range_error("There are no elements in the stack.");
}
The stack uses linked nodes for storage, so first_ is a pointer to the first node.
Why am I getting this error?
Your
checkElements()function is not marked asconstso you can’t call it onconstqualified objects.top(), however is const qualified so intop(),thisis a pointer to a constStack(even if theStackinstance on whichtop()was called happens to be non-const), so you can’t callcheckElements()which always requires a non-constinstance.