In the following code, I'm not able to pass a temporary object as argument to the printAge
function:
struct Person {
int age;
Person(int _age): age(_age) {}
};
void printAge(Person &person) {
cout << "Age: " << person.age << endl;
}
int main () {
Person p(50);
printAge(Person(50)); // fails!
printAge(p);
return 0;
}
The error I get is:
error: invalid initialization of non-const reference of type ‘Person&’ from an rvalue of type ‘Person’
I realize that this is something to do with passing an lValue to a function expecting a rValue... Is there a way to convert my lValue to rValue by using std::move or something? I tried taking a constant parameter, but that does not seem to work.
const
lvalue reference instead. – Monmouthshire