Possible Duplicate:
C++ functions: ampersand vs asterisk
What are the distinctions between the various symbols (*,&, etc) combined with parameters?
I am wondering the difference between the address operator &
and the deference operator *
in a C++ function call. For example take the following function
void foo (std::string& param)
{
param = "Bar.";
std::cout << param.size();
}
and let's call it in our main()
function like so...
int main()
{
std::string test;
foo(test); //Why not foo(&test)?
std::cout << test; //Prints out the value "Bar."
}
First off, why does the &
operator allow me to assign a value as if it were a pointer (assigning it a value that survives the RAII and scope of the function foo()
when it's not a pointer) as it is able to be printed out in my main()
function even though it's not static
? I am assuming it is not a pointer because I am able to access the size()
method by using the .
operator instead of the ->
which is used for pointers.
Secondly, what would be the difference between using the &
operator in a function parameter vs. using the *
operator? Is it even different than just a plain variable like std::string param
? It appears to be called like that (foo(test)
instead of foo(&test)
).