Question

I have a problem with overloading the postfix '--' operator. Instead of it being called at the end of the code line, just like this simple example with an Integer type:

int test = 5;
cout << test-- << endl; //Output1: 5
cout << test << endl; //Output2: 4

Instead, it is being called right away, and not at the end.

Note: LinkList is a class that I've built with different operators to work with it:

operator+= adds the given number to the start of the list, and operator--(int) deletes the last data member. The operator<< simply prints the list in order.

LinkList l1;
l1+=1;
l1+=2;
l1+=3;
l1+=4;
l1+=5;
cout << l1 << endl; //Output1: 5 4 3 2 1
cout << l1-- << endl; //Output2: 5 4 3 2
cout << l1 << endl; //Output3: 5 4 3 2 

I know that I can just work around it by calling the operator after the cout command, but how is it possible to make it work just like with the integer example (where output2 should have the same output at output1)?

Here is the function of the operator:

//Deletes the last node
LinkList LinkList::operator--(int){
    if(list){ //If the list isn't empty
        if(list->NextNode()){ //If there in another node
            Node* newLast = (*this)[list_size - 2]; //Store the new last node
            delete newLast->NextNode(); //Delete the last node
            newLast->InsertNext(NULL);
        }//if
        else{ //The head is the only node
            delete list; //Delete the head
            list = NULL; //The list is now empty
        }//else
        list_size--; //Update the list size
    }//if
    return *this;
}//end operator--(int)

Thanks

Was it helpful?

Solution

You need at first to create a copy of the current list and after that change the current list. And the copy has to be returned. In your example you return a copy of already changed list.

Also take into account that when you use an overloaded operator function there is no side effects as with the built operator.

For example the function could look as provided that the copy constructor is valid

//Deletes the last node
LinkList LinkList::operator--(int){
    LinkList currentList( *this );

    if(list){ //If the list isn't empty
        if(list->NextNode()){ //If there in another node
            Node* newLast = (*this)[list_size - 2]; //Store the new last node
            delete newLast->NextNode(); //Delete the last node
            newLast->InsertNext(NULL);
        }//if
        else{ //The head is the only node
            delete list; //Delete the head
            list = NULL; //The list is now empty
        }//else
        list_size--; //Update the list size
    }//if
    return currentList;
}//end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top