0

I understand the use of foo(const int& a). This can be used to call something like foo(1) where for foo(int& a) will fail.

Now experimenting I created this class:

class temp {
public:
    int a;
    temp(int x = 5) : a(x) {}
    void foo_val(temp a) { /* ... */ }
    void foo_ref(temp& a) { /* ... */ }
}; 

void main() {
    temp temp1(6);
    temp1.foo_val(temp1); // foo_val(temp a) is called
    temp1.foo_ref(temp()); // foo_ref (temp& a) is called
}

What I don't understand is why does the temp1.foo_ref(temp()) succeed. How can we have a reference with a rvalue (temp() in this case). I was expecting it to succeed only with foo_ref(const temp& a). Am I thinking about rvalue incorrectly.

Will
  • 24,082
  • 14
  • 97
  • 108
Arul Moondra
  • 131
  • 1
  • 9

1 Answers1

3

What I don't understand is why does the temp1.foo_ref(temp()) succeed.

Judging by use of void main() { ... }, you must have an old or non-standards compliant compiler.

temp1.foo_ref(temp());

should fail. I get the following error using g++ 4.8.4.

g++ -Wall -std=c++11     socc.cc   -o socc

socc.cc: In function ‘int main()’:
socc.cc:13:22: error: no matching function for call to ‘temp::foo_ref(temp)’
  temp1.foo_ref(temp()); //foo_ref (temp& a) is called
                      ^
socc.cc:13:22: note: candidate is:
socc.cc:6:7: note: void temp::foo_ref(temp&)
  void foo_ref(temp& a){}
       ^
socc.cc:6:7: note:   no known conversion for argument 1 from ‘temp’ to ‘temp&’
R Sahu
  • 204,454
  • 14
  • 159
  • 270