Overloading the function call operator () is powerful, because functions can take an arbitrary number of comma-separated parameters. In a customized String
class, for example, you could overload this operator to select a substring from a String
—the operator’s two integer parameters could specify the start location and the length of the substring to be selected. The operator()
function could check for such errors as a start location out of range or a negative substring length.
The overloaded function call operator must be a non-static member function and could be defined with the first line:
String String::operator()( size_t index, size_t length ) const
In this case, it should be a const
member function because obtaining a substring should not modify the original String
object.
Suppose string1
is a String
object containing the string "AEIOU"
. When the compiler encounters the expression string1(2, 3)
, it generates the member-function call
string1.operator()( 2, 3 )
which returns a String
containing "IOU"
.
Another possible use of the function call operator is to enable an alternate Array
subscripting notation. Instead of using C++’s double-square-bracket notation, such as in chessBoard[row][column]
, you might prefer to overload the function call operator to enable the notation chessBoard(row, column)
, where chessBoard
is an object of a modified two-dimensional Array
class. The primary use of the function call operator is to define function objects, which we discuss in Chapter 16.