3

I have a person object with attributes such as name, surname, etc...I also have 3-4 classes which inherit from the person class.

I have another class which will print all the different types of person in ascending order. So, I have overloaded the operator '<' and I know it works as I have used it elsewhere. But for some reason, it is not being used in this specific method which is in a different class.

this is my overloading method found in the person class.

    bool person::operator< ( const person &p2 ) const
    {    
        if ( surname() < p2.surname() )
           return true;
        else 
        //There are many other conditions which return true or false depending on the attributes.
    }

This is the method found in another class (a subclass) which should use the overloaded operator but does not seem to make use of it.

 vector<person *> contacts::sorted_contacts() const{

    vector<person *> v_contact;

    auto comparison = [] ( person *a, person *b ){  return a < b ;  };  

    //Some code here which fills in the vector

    sort(begin(v_contact), end(v_contact), comparison);
}

The sort here does not work. Because, when I use copy/paste the implementation of the overloading and put it here, the vector is sorted correctly. Because I want to re-use code, I'm trying to figure out why the operator < is not being used here.

5
  • Pointers already have an operator<. It's impossible to provide your own.
    – chris
    Dec 3, 2013 at 17:45
  • 1
    Your overloaded < won't work for container elements as pointers
    – P0W
    Dec 3, 2013 at 17:46
  • @chris: Unless, like here, you provide a comparator argument to sort. But that should compare the objects, rather than the pointers. Dec 3, 2013 at 17:46
  • 2
    write *a < *b instead.
    – erenon
    Dec 3, 2013 at 17:46
  • @MikeSeymour, Yeah, I'm not honestly completely sure what I was going for.
    – chris
    Dec 3, 2013 at 17:48

2 Answers 2

9

Here

auto comparison = [] ( person *a, person *b ){  return a < b ;  }

you are comparing pointers instead of comparing the objects themselves.

In order to compare the actual objects (which apparently was your intent) you have to dereference the pointers. It also makes sense to const-qualify your pointers properly

auto comparison = [] ( const person *a, const person *b ){  return *a < *b ;  }
1
  • Thank you. I cannot believe that I did not see that:'( Thanks!
    – mokko211
    Dec 3, 2013 at 17:49
4
auto comparison = [] ( person *a, person *b ){  return a < b ;  }

compares the pointers, not the persons.

auto comparison = [] ( person *a, person *b ){  return *a < *b ;  }

will compare the persons.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.