Pass by Reference C++ style
In
C++ we make use of the reference parameter. All you need to do is put &
before your function's parameter. Example : void square (& x)
Whatever operation is done on x will actually affect the original calling
argument. Basically x can be said to be an implicit pointer. The difference is
that you needn't use *x to operate on the parameter. I'll show you with an
example (the same square function example).
// Pass by reference C++ style example
void square
( int &x )
// x becomes a reference parameter
{
x = x * x;
// no need to say *x = (*x) * (*x); as we did in
the last section
}
int main ( )
{
int a =10;
int answer;
square(a);
// No need to say &a as we did in the previous section
cout<<" Value of a is "<<a;
// Value of a is 100
return 0;
}
The line x = x * x ; actually operates on a and not on a copy of a.
The next section is a : Test Yourself section
or go back to the Contents page 2