References were introduced to C++ to get rid of using pointers for passing
params via reference. The normal way for this in C was:

foo(const param_type* param_name);

But in the function foo you always had to write *param_name, and if you call
foo, you had to use the &-operator for the param. If you use a reference
variable, your code becomes more readable (in my opinion). In the end, it is
the same mechanism, BUT:

>   void changetemp( float& );
>
>   int main()
>    {
>      float temp = 25;
>
>      cout << "temp is: " << temp << " deg F \n";
>      changetemp(temp);
>      cout << "temp is now: " << temp << "deg F \n");
>
>     exit(0);
>    }
>
>    void changetemp( float& tmp )
>     {
>       tmp += 5;
>      }


Generally speaking, it is a bad way to use a reference like this (because
you dont really want side effects on the params you pass to a function). The
most often used way, reference variables are used, is:

foo(const param_type& param_name);

With const you ensure that there are no side effects. And if param_type is a
complex struct, you also avoid copying the entire struct to a local stack
object, what could be a time consuming operation. In C++ passing params by
value could be even worse, because the copying is done via the copy
constructor. That could lead to several calls to copy constructor of members
in this class.

What is more, sometimes you have classes with ownerships (like streams). If
you pass such an object via value, the newly created local object in the
function will get the ownership over the stream via the copy constructor. If
you leave the function, the local object is destroyed and therefore its
destructor will be called. This leads to closing the stream. Therefore we
have a side effect, despite of passing the object via value! (This is also a
hard to find error, because your program will only fail, if you try another
operation on the stream, after calling the function, which functioned in a
proper way.)


Michael Tamm
[EMAIL PROTECTED]

TODO: insert intelligent saying here

Reply via email to