c++functiondereferenceaddress-operator

Difference between the * and & operator in function calls


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)).


Solution

  • & function parameter specifically signifies that this parameter is being passed-in by reference (traditionally compilers implement this as a pointer) which is why you see the effect of this assignment in your main(). static would have nothing to do with that.

    The difference in declaring a parameter to a function using & and * is that the second one allows a nullptr (or a non-existent or just a plain invalid address) to be passed-in while the & guarantees that there's a real object being referenced by this function's argument. Other than that both provide similar functionality of allowing an original object to be changed via it's reference.