Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Call-by-Reference

There are two mechanisms for passing parameters into C++ functions:

  • Call-by-value
  • Call-by-reference

With call-by-value, just the value is passed into a function. The function can then change this value as required, but the modified version is not reflected back to the caller.

For changes to be made, you must use call-by-reference. The only difference is the use of the ampersand (&) character. Listing 6 shows an example of a function that uses both mechanisms.

Listing 6 A function that uses call-by-value and call-by-reference

void testCallByReference(int& anInt, int anotherInt)
{
Console::Write("Values of the parameters: ");
Console::Write(anInt);
Console::Write(" ");
Console::WriteLine(anotherInt);
anInt = 100;
anotherInt = 200; }

The first parameter (anInt) in the function testCallByReference() is passed by reference, and the second (anotherInt) is passed by value.

Listing 7 illustrates the parameters being initialized and printed. The parameters are then passed into testCallByReference().

Listing 7 Calling the testCallByReference() function and passing parameters

int anInt = 10;
int anotherInt = 30;
Console::Write("Starting values of the parameters: ");
Console::Write(anInt);
Console::Write(" ");
Console::WriteLine(anotherInt);

testCallByReference(anInt, anotherInt);

Console::Write("Finishing values of the parameters: ");
Console::Write(anInt);
Console::Write(" ");
Console::WriteLine(anotherInt);

Execution of the code in Listing 7 results in the program output of Figure 6.

Figure 6

Figure 6 Passing by value and by reference

You can see in Figure 6 that it is only the first parameter that changes across the invocation of the function testCallByReference().

One question concerning value and reference calling is this: Why not just make all parameters call-by-reference? There are two reasons: side effects and privacy. Side effects are caused by inadvertent changes to data; for example, if a change is made to a call-by-reference parameter.

Being able to change a parameter in this way also potentially violates data ownership. So, it’s better to use call-by-value as your default and use call-by-reference only when data changes are expected. You wouldn’t think that an ampersand character in a function parameter list could have such important design consequences!

C++ was among the first of the object-oriented languages that specifically targeted the PC platform. Inheritance is one of the key advantages of C++ because it presents many opportunities for economical solutions. Let’s have a look at some examples.

  • + Share This
  • 🔖 Save To Your Account