mokko211
mokko211

Reputation: 607

C++ Overloading of operator '<' is not being used every time

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.

Upvotes: 3

Views: 224

Answers (2)

Emilio Garavaglia
Emilio Garavaglia

Reputation: 20730

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.

Upvotes: 4

AnT stands with Russia
AnT stands with Russia

Reputation: 320371

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 ;  }

Upvotes: 9

Related Questions