I think this is what your book is trying to explain:
Code:
#include <iostream>
using namespace std;
void changeIt(int& num)
{
--num;
}
int main ()
{
int n = 10;
changeIt(n);
cout<<n<<endl; //As expected the function changes n.
double d = 3.5;
changeIt(static_cast<int>(d));
cout<<d<<endl; //Does the function change d?
return 0;
}
Your book says that the typecast of d creates a temporary variable which is passed to the function. The function then ends up changing the temporary variable, so d is unchanged by the function.
However, the example won't even compile in VC++6. I get an error on the line that calls print():
error C2664: 'print' : cannot convert parameter 1 from 'int' to 'int &'
A reference that is not to 'const' cannot be bound to a non-lvalue
So, this warning rings hollow:
Then changes to the formal parameter in the invoked function would change the temporary variable (instead of the original), leading to hard-to-find bugs.
I don't know why the compiler won't let you change a temporary variable--maybe that's the nature of a temporary variable.
Is the temporary variable constant (const) ?
It appears so since this compiles:
Code:
#include <iostream>
using namespace std;
void changeIt(const int& num)
{
//but now you can't change the parameter variable
//inside the function
}
int main ()
{
int n = 10;
changeIt(n);
cout<<n<<endl;
double d = 3.5;
changeIt(static_cast<int>(d));
cout<<d<<endl;
return 0;
}