Method call acting unexpectedly like an l-value

Viewed 807

Can anybody explain why this code compiles:

typedef struct longlong
{
  unsigned long low;
  long high;
}
longlong;

typedef longlong Foo;    

struct FooStruct
{
private:
  Foo bar;

public:
  void SetBar(Foo m)
  {
    bar = m;
  }

  Foo GetBar()
  {
    return bar;
  }
};

int main()
{
  FooStruct f;
  Foo m1 = { 1,1 };
  Foo m2 = { 2,2 };
  f.SetBar(m1);
  f.GetBar() = m2;     // Here I'd expect an error such as
                       // "error: lvalue required as left operand of assignment"
}

I expected the compilation to fail with error: lvalue required as left operand of assignment on line f.GetBar() = m2; because IMO f.GetBar() is not an l-value, but it compiles seemlessly and f.GetBar() = m2; is a NOP.

On the other hand if I replace the typedef longlong Foo; by typedef long Foo;, the line mentioned before won't compile and I get the expected error.

I came along this issue while refactoring some old code. The code in this question has no purpose other than to illustrate this issue.

4 Answers
Related