I was hoping someone could explain to me why a function with a reference parameter would be called rather than one with a pointer parameter, given something like the following:
int Func1 ( int & a );
int Func1 ( int * a );
int main()
{
int y = 1;
int & x = y;
int * z = & y;
Func1(y); // Calls reference version
Func1(&y); // Calls pointer version
Func1(z); // Calls pointer version
return 0;
}
int Func1 ( int & a )
{
cout << "Reference param Func1 called" << endl;
a = a + 1;
return a + 1;
}
int Func1 ( int * a )
{
cout << "Pointer param Func1 called" << endl;
*a = *a + 1;
return *a + 1;
}
I'm confused as to how the decision is made to call the pointer parameter version of Func1 for the Func1(&y) call rather than the reference parameter version of Func1. Also, why is the reference parameter version of Func1 not chosen for the Func1(z) call? If z holds an address, I don't see why the address can't be passed into the reference parameter for Func1( &a ).
int Func1 ( int & a );
matches calls where the argument expression has typeint
(and is eligible to have a non-const reference taken to it).int Func1 ( int * a );
matches calls where the argument expression has typeint*
.Well, you could achieve that by calling
Func1(*z)
.