Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No match for operator > when using with a function

I have overloaded the following greater than operator:

bool operator > (Person & a, Person & b)
{
   //firstname is a string data type
   return (a.FirstName > b.FirstName);      
}

Which works fine if I have something like the following:

Person a = myPersonA;
Person b = myPersonB;

return myPersonA > myPersonB;

However, within my Person class I have defined a Person getByID(int id) function, which returns an instance of a Person, by the given ID. If I try to use my operator with the returned values from this function like this:

bool whosGreater = listPeople.getById(1) > listPeople.getById(2);

I get "Error: no match for operator >(Person&, Person&)"

but if I do the following it works fine:

Person a = listPeople.getById(1);
Person b = listPeople.getById(2);
bool whosGreater = a > b;

Is there something I am not seeing here? It seems to me it should work.

PS: This is for a homework, so I could really get away with declaring the variables and assign them what the functions return and get away with it, but I would like to know what is happening so that I can learn. I have tried googling it, but I can't come up with the right question.

like image 596
Hanlet Escaño Avatar asked Dec 20 '22 03:12

Hanlet Escaño


2 Answers

The returned value from a function is a temporary value, not a "normal" Person object. Temporary values can only be passed in as const parameter references, so changing your parameters to const references should work well;

bool operator > (const Person & a, const Person & b)
{
   //firstname is a string data type
   return (a.FirstName > b.FirstName);      
}
like image 129
Joachim Isaksson Avatar answered Dec 24 '22 02:12

Joachim Isaksson


Make it:

bool operator > (Person const & a, Person const & b)
{
   //firstname is a string data type
   return (a.FirstName > b.FirstName);      
}

Normal references cannot bind to temporary objects (as the one returned by getById()). And you are not mutating passed in objects, so make the references const.

like image 32
Tomek Avatar answered Dec 24 '22 00:12

Tomek