Reputation: 181
So i have a custom stack class and a top function. Im checking if the top is empty but am having some trouble returning a value without error.
Error: "Cannot convert int to &int"
dataType &top()
{
try
{
if (stackData.checkEmpty()== false)
{
throw stackData.size();
}
}
catch(...)
{
cout << "Stack size is zero. Can not retrieve top " << endl;
return stackData.size(); //***Where the problem is***
}
return stackData.back();
}
int size( ) const
{
return Size;
}
Upvotes: 1
Views: 15681
Reputation: 2053
The problem is in your size method. You must be returning an rvalue or a literal. See this post for the same problem in a different setting.
Evaluate whether you really need to return a reference, since it is meaningless to have references to the top element when the stack is empty. It may be better to follow other's suggestions and throw an exception when top is called on an empty stack, returning the size of the stack will make virtually impossible to distinguish the empty case (that'd return zero) from when a zero integer is stored in the stack.
As a side note, for brevity, is it better to write:
if (!stackData.checkEmpty())
than
if (stackData.checkEmpty()== false)
since checkEmpty() is already returning a boolean. This is just style.
Upvotes: 2
Reputation: 138
stackData.checkEmpty() reads like it returns true if empty but you test for false and throw which seems the wrong way round.
Your function top() has a signature to return dataType& but on this condition you return an int... you can't do that.
Upvotes: 0