user123454321
user123454321

Reputation: 1058

C++ stack implementation - two versions of top method

I have to implement two methods in C++

int& stack::top();
int stack::top() const;

As far as I understand the first one allows me to write something like this:

myStack->top() = 500 // now the top element is 500

I dont know what is the purpose of 2nd method.

Upvotes: 2

Views: 103

Answers (2)

Benjamin Lindley
Benjamin Lindley

Reputation: 103733

The const at the end of

int stack::top() const;

means that the stack object on which this function is called is const. When you have a const stack, you don't want to call the first function, because it allows non const access to the top element of the stack. The lack of const at the end of the first function ensures that it can't be called on a const object.

But you still want to be able to at least examine the value of the top of the stack, even if it is const (or more commonly, is being accessed through a const reference). That's what the second function is for. For example:

int getTop(const stack& st)
{
    return st.top();
}

This (admittedly useless) function wouldn't compile without the second function, because the first one cannot be called on a const stack.

Upvotes: 2

Mats Petersson
Mats Petersson

Reputation: 129454

The second one is useful if you do something like this:

bool isTopMoreThan(const stack st, int val)
{
   return st.top() > val;
}

Or any other time you have a const stack object.

Upvotes: 2

Related Questions