Petr
Petr

Reputation: 14495

Overloading of operators and issue with invalid operands to binary expression

I made a class Foo for which I overloaded operators < > <= >= != and = now I have these 2 codes, both should do same, but only 1 works:

This works:

Foo foo = Foo("1");
if (foo <= something->foo) { ...

This doesn't work:

if (Foo("1") <= something->foo) { ...

The error in second version is:

invalid operands to binary expression. Candidate function not viable: expects an l-value for 1st argument.`

What does it mean and why it doesn't work?

Upvotes: 2

Views: 4440

Answers (1)

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39380

You wrote your operator in such a way that forbids passing in rvalues; an example might be, as pointed out by @TartanLlama, taking non-const reference.

bool operator<= (Foo& a, Foo& b); // will err
bool operator<= (const Foo& a, const Foo& b); // will work fine

The reason for that not working is that it's simply disallowed in C++.

Upvotes: 6

Related Questions