mr0il
mr0il

Reputation: 71

Overloaded Comparison Operator Not Working

I am trying to compare two objects of my class CustomerNode, and then return a result related to the alphabetic superiority of these methods. I cannot figure out exactly why this isn't working. To me, the logic seems good, and I am following the instructions set forth in my homework.

    bool OrderedList::add (CustomerNode* newEntry)
{
if (newEntry != 0)
{
    CustomerNode * current;
    CustomerNode * previous = NULL;
    if(!head)
        head = newEntry;
    current = head;
  // initialize "current" & "previous" pointers for list traversal
   while(current && *newEntry < *current) // location not yet found (use short-circuit evaluation)
   {
    // move on to next location to check
    previous = current;
    current = current->getNext();
   }

  // insert node at found location (2 cases: at head or not at head)
  //if previous did not acquire a value, then the newEntry was
  //superior to the first in the list. 
  if(previous == NULL)
    head = newEntry;
  else
  {
    previous->setNext(newEntry); //Previous now needs to point to the newEntry
    newEntry->setNext(current); //and the newEntry points to the value stored in current.
  }
}
    return newEntry != 0;  // success or failure
    }

Okay, here is the overloaded operator< included in the program, testing it on generic objects turns up expected results:

    bool CustomerNode::operator< (const CustomerNode& op2) const
    {
       bool result = true;
       //Variable to carry & return result
       //Initialize to true, and then:
       if (strcmp(op2.lastName, lastName))
        result = false;

        return result;
       }

I am very new to programming, so I appreciate any responses, especially style critiques since I am still learning that. Is my logic just wrong, or are there other rules that I need to be aware of? I do not entirely understand why my parameters are reference, or if I actually need to dereference the parameter to call the operator.

Thanks.

Upvotes: 0

Views: 255

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258548

Your condition is wrong:

if (strcmp(op2.lastName, lastName))

For different strings, regardless of their ordering, this will return not-false (true), and your function will return false.

A correct condition would be:

if (strcmp(op2.lastName, lastName) >= 0)

Or you can just re-write the whole thing:

bool CustomerNode::operator< (const CustomerNode& op2) const
{
   return  strcmp(op2.lastName, lastName) < 0;
}

Upvotes: 2

Related Questions