user3341399
user3341399

Reputation: 81

Overloaded > operator returns true when it should be returning false

I have attempted to overload the > operator so that I can see which Polynomial object is greater in regard to how many terms are in the Polynomial (example - if Polynomial1 had 4 terms and Polynomial2 had 3 terms, Polynomial1 > Polynomial2 would return true. My Polynomial objects are linked lists, so I thought I would traverse each list and make a counter variable for each. For each node (term) encountered, the counter would be upped by 1. However, when I try this function out in main, it returns True for a lists that are equal in number of terms.

bool Polynomial::operator>(const Polynomial &other ) const
{
    int countA;
    int countB;
    shared_ptr<Polynomial::Term> a = this->head;
    shared_ptr<Polynomial::Term> b = other.head;

    for(a; a!=nullptr; a = a->next)
    {
        countA++;
    }
    for(b; b!=nullptr; b = a=b->next)
    {
        countB++;
    }
    if(countA > countB)
    {
        cout << "Greater then" << endl;
        return true;
    }
    else
    {
        cout << "less then or equal to" << endl;
        return false;
    }
}

Upvotes: 0

Views: 129

Answers (3)

Mike Seymour
Mike Seymour

Reputation: 254431

You need to initialise countA and countB to zero.

Upvotes: 3

DevelopmentFun
DevelopmentFun

Reputation: 44

Your error is in the second for loop. b = a = b->next. It should read b = b->next.

Upvotes: 0

ikh
ikh

Reputation: 10417

Never forget initializations :)

int countA = 0;
int countB = 0;

Upvotes: 4

Related Questions