I have a function printInt like below.
void printInt(const int& a)
{
cout<<a<<endl;
}
When I call like function using the following arguments like
int a=5;
printInt(a);
printInt(5);
It works perfectly. But when I change the function definition to
void printInt(int& a)
{
cout<<a<<endl;
}
This gives error to the call printInt(5)
. Now my question is why const int&
is both a lvalue and rvalue reference whereas int&
is only a lvalue reference. As far as I know int&&
is a rvalue reference. So how a single & can refer to an rvalue reference?
To summarize my problem:
Lvalue reference parameter
void printInt(int& a)
{
cout<<a<<endl;
}
Rvalue reference parameter
void printInt(int&& a)
{
cout<<a<<endl;
}
Both lvalue and rvalue. but how?
void printInt(const int& a)
{
cout<<a<<endl;
}
const int&
is an lvalue reference. The thing is that the language specifies that it can bind to rvalues. int&
is also an lvalue reference, but it cannot do that. That is why the first version works and the second doesn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With