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.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With