-1

having the error in the header in visual studios everytime i call dequeue function. pop function works for stack but when it comes to queues it doesnt work and error comes while debugging.

in queue.cpp

std::string &Queue::dequeue()
{
    if (inbox.isEmpty(inbox))
    {
        std::cout << "The queue is empty!";
        return inbox.pop(inbox);
    }
    else
        return inbox.pop(inbox);
}

in stack.cpp

bool stack::isEmpty(stack& stack1)
{
    if (stack1.value =="")
        return true;
    else
        return false;
}


std::string stack::pop(stack &stack1)
{
    if (isEmpty(stack1))
    {
        std::cout << "The stack is empty ";
        return stack1.value;
    }
    else
    {
        if(stack1.next != NULL)
        {
            std::string val1 = stack1.value;
            stack1 = *stack1.next;
            return val1;
        }
        else
        {
            std::string val2 = stack1.value;
            stack1.value="";
            stack1.next = NULL;
            return val2;
        }
    }
}

1 Answers1

1

return inbox.pop(inbox); should fail to compile. inbox.pop(inbox) is an rvalue so it cannot bind to a non-const reference.

Possibly you have enabled a compiler extension to allow this binding (I think MSVC defaults to doing this), however you still return a reference to an object that no longer exists, causing undefined behaviour. (The temporary string returned by pop() only lives up to the next ;, then it is destructed).

To fix this, change

std::string &Queue::dequeue()

to

std::string Queue::dequeue()

(obviously, change the function declaration too).

You haven't provided enough code to be able to tell for sure whether stack::pop has any bugs (although it does seem a bit strange). Show the class definition of stack and its constructors at least.

M.M
  • 138,810
  • 21
  • 208
  • 365