LeonS LeonS - 3 months ago 29
C++ Question

C++ operator < overloading

I have a problem with overloading of the < operator.
I have this class:

WordEntry.h:

class WordEntry
{
public:
WordEntry(string word);
~WordEntry();

bool operator<(const WordEntry otherWordEntry);

string getWord();

private:
string _word;
};


WordEntry.cpp(I removed constructor & destructor):

string WordEntry::getWord()
{
return _word;
}


bool WordEntry::operator<(WordEntry otherWordEntry)
{
return lexicographical_compare(_word.begin(),_word.end(),otherWordEntry.getWord().begin(),otherWordEntry.getWord().end());
}


Everything is fine when I'm using it in main.cpp like that:

WordEntry w1("Der");
WordEntry w2("das");

if (w1.operator<(w2)) {
cout << "w1 > w2";
}
else
{
cout << "w2 > w1";
}


But when I call
sort()
on a
vector
with
WordEntry
objects, I'll get the error message


Invalid operands to binary expression ('const WordEntry' and 'const
WordEntry')


and it points to
stl_algo.h
.

Does anyone knows what's going on here?

Answer

Right now the argument to < is const but the member is not. This means a < comparison between 2 const WordEntry& objects will fail because it can't bind to <. You need to make the member and the argument both const

bool operator<(const WordEntry& otherWordEntry) const;

bool WordEntry::operator<(const WordEntry& otherWordEntry) const {
  ...
}

Note: As pointed out in the comments you should also pass WordEntry by reference