Austin Hyde
Austin Hyde

Reputation: 27446

Discards qualifiers error

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?

Upvotes: 11

Views: 35259

Answers (4)

anon
anon

Reputation:

Because checkElements() isn't declared const.

void checkElements() const {
    if (first_==NULL || size_==0)
        throw range_error("There are no elements in the stack.");
}

Without that declaration, checkElements cannot be called on a const object.

Upvotes: 2

Dave Bacher
Dave Bacher

Reputation: 15982

You're calling a non-const method from a const method.

Upvotes: 4

CB Bailey
CB Bailey

Reputation: 792427

Your checkElements() function is not marked as const so you can't call it on const qualified objects.

top(), however is const qualified so in top(), this is a pointer to a const Stack (even if the Stack instance on which top() was called happens to be non-const), so you can't call checkElements() which always requires a non-const instance.

Upvotes: 22

You cannot call a non-const method from a const method. That would 'discard' the const qualifier.

Basically it means that if it allowed you to call the method, then it could change the object, and that would break the promise of not modifying the object that the const at the end of the method signature offers.

Upvotes: 13

Related Questions