Antar Roy
Antar Roy

Reputation: 25

Overloaded Double Equal operator is not working as expected

its a long doubly linked list code. but the problem is when i overload the operator, i think the function is not getting called. I have tried to put a debugging line printing here, but that does never show up. so i wanted if two of my Doubly Linked List are equal , it should print true.

class Node
{
    friend class Dlist;
private:
    string s;
    string language;
    int noOfNode;
    Node * Next;
    Node * Prev;
};


class Dlist
{
private:
    Node * Header;
    Node * Trailer;
    int n;

public:
    Dlist();//default constructor
    void AddFront(string e,string lang);
    void Print();
    void AddBack(string e,string lang);
    void RemoveFront();
    void RemoveBack();
    int Empty(){ if (Header->Next==Trailer) return 1 ; else return 0;}
    int CountLanguage(string lang);
    int search (string r);
    void RemoveWord(string tempW);
    void changeIndex(Node* node,int newIndex);
    void sortDLL();
    void PrintRev();
    void AddInOrder(string s, string language);
    bool operator==(const Dlist &Q);
};
bool Dlist::operator ==(const Dlist &Q)
{
    Node*tempL1=Header->Next;
    Node *tempL2=Q.Header->Next;
    int count=0;
    cout<<"here"<<endl;
    if(n==Q.n)
    {
        while(tempL1!=Trailer && tempL2!=Q.Trailer)
        {
            if(tempL1->s==tempL2->s && tempL1->language==tempL2->language
                ){
                tempL1=tempL1->Next;
                tempL2=tempL2->Next;
            }
            else return false;
        }
        return true;
    }
    else
    return false;

}
int main()
{
    Dlist *x = new Dlist;
    Dlist *y = new Dlist;
    Dlist *z = new Dlist;

    inputX();
    inputY();
    cout<<endl<<"test if the first list and the second are equal?? :"<<endl;
    cout<<(x==y)<<endl;
    return 0;
}

Upvotes: 1

Views: 124

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

For starters the operator should be declared with the qualifier const

bool operator==(const Dlist &Q) const;

In this statement

cout<<(x==y)<<endl;

the used expression is a comparison of two pointers x and y declared like

Dlist *x = new Dlist;
Dlist *y = new Dlist;

You need to compare the pointed objects like

cout<<( *x == *y )<<endl;

Pay attention to that there is a logical error in this code snippet

    while(tempL1!=Trailer && tempL2!=Q.Trailer)
    {
        if(tempL1->s==tempL2->s && tempL1->language==tempL2->language
            ){
            tempL1=tempL1->Next;
            tempL2=tempL2->Next;
        }
        else return false;
    }
    return true;

Instead of the statement

    return true;

you should write

    return tempL1 == Trailer && tempL2 == Q.Trailer;

Upvotes: 2

Related Questions