void triple(int& value){ value *= 3; }

Now when triple() finishes, the variable passed in has increased three-fold. The classic swap function could be defined as follows:

template <class T> void swap(T& a, T& b){ T temp = a; a = b; b = temp; }

If a and b were instead passed by value, the swap function would not work as intended.


Structs have been made all but obsolete by the introduction of classes to C++, but they are worth mentioning as a way to encapsulate data. They are used to keep track of collections of variables which ought to go together for some reason. Consider a Cartesian plane. To specify a point on the plane, you need to give two values: an x coordinate and a y coordinate. You can create a structure type to keep track of points:

struct position{ float xcoor; float ycoor; } p1, p2; position p3;

The above code creates three position types. The first two are created immediately after the struct definition, and the third is created separately. The position variables have no value at this point, but you can access their components with the . operator:

p1.xcoor = 5.0; p1.ycoor = 7.3;

Sometimes you will have a pointer to a struct type, for example when creating a linked list. To access a data member of the struct pointer, you use the membership access operator ->:

position* pos_pointer = &pos; pos_pointer->xcoor = 6.1;

You could also use the dot notation (*pos_pointer).xcoor, but this is uncommon and somewhat cumbersome, making it potentially confusing.