2

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?

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
Petr
  • 13,747
  • 20
  • 89
  • 144

1 Answers1

6

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++.

Community
  • 1
  • 1
Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135