Passing Function Arguments by Reference

In Hour 5, “Functions,” you learned that functions have two limitations: Arguments are passed by value, and the return statement can return only one value.

Passing values to a function by reference can overcome both of these limitations. In C++, passing by reference is accomplished in two ways: using pointers and using references. The syntax is different, but the net effect is the same: Rather than a copy being created within the scope of the function, the actual original object is passed into the function.

Passing an object by reference enables the function to change the object being referred to.

Listing 11.4 creates a swap function and passes in its parameters by value.

Listing 11.4. Demonstrating Pass ...

Get Sams Teach Yourself C++ in 24 Hours, Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.