Logo Data Structures and Algorithms with Object-Oriented Design Patterns in C++
next up previous contents index

Constant Parameters

In general, pass-by-reference parameter passing allows the called function to modify the actual parameters. However, sometimes it is the case that the programmer does not want the actual parameters to be modified. Nevertheless, pass-by-reference may be the preferred method for performance reasons.

In C++ we can use the const keyword to achieve the performance of pass-by-reference while at the same time ensuring that the actual parameter cannot be modified. Consider the following definition of the function Two:

void Two (int const& x)
{
    x = 2; // Not allowed.
    cout << x << endl; // This is ok.
}
The const keyword modifies the type int. It says that the int to which x refers is a constant. The value of x can be used without impunity. However, x cannot be used as the target of an assignment statement. In fact, the variable x cannot be used in any context where it might be modified. Any attempt to do so is an error that is detected by the compiler.


next up previous contents index

Bruno Copyright © 1997 by Bruno R. Preiss, P.Eng. All rights reserved.