
-----------------------------------
wtd
Wed Mar 30, 2005 12:34 am

Using const and references
-----------------------------------
When we pass parameters in C++, by default we make a copy of the thing we're passing in.  There are a few practical problems with this:

For one, we can't make changes to that variable passed in.  If I have:

void read(int a)
{
   std::cin >> a;
}

int main()
{
   int foo = 42;

   read(foo);

   return 0;
}

Then I haven't actually changed foo at all from its initial value of 42.

The other problem is that passing by value means using memory, and CPU time is spent copying data around.

The solution?

References.  We add a little & to the end of the type name and now we have not the value of the variable, but the variable itself.

void read(int& a)
{
   std::cin >> a;
}

int main()
{
   int foo = 42;

   read(foo);

   return 0;
}

Eureka!  It works.  Now we've tackled the problem of pass-by-value.  

This also solves the problem of lots of memory being copied.  It raises another problem though.  Now we can make changes to the variable being passed in.  Sometimes we distinctly do not want to do this.

Let's create a basic Name class with a friend operator for output.

class Name
{
   private:
      std::string first, last;
   public:
      Name(std::string f, std::string l) : first(f), last(l) { }
   
      friend std::ostream& operator