19.8.3. The Function-Call operator()

[ fromfile: useroperators.xml id: fncalloperator ]

The function call operator() is over-loadable as a non-static member function. It is frequently used to provide a callable interface, an iterator, or a multiple index subscript operator. It is more flexible than operator[], because it can be overloaded with respect to different signatures. In Example 19.9, we have a multiple-subscript operator for a Matrix class.

Example 19.9. src/operators/matrix/matrix.h

[ . . . . ]
class Matrix {
public:
    Matrix(int c, int r);
    Matrix(const Matrix& m);
    ~Matrix();
    double& operator()(int i, int j);
    double operator()(int i, int j) const;
    Matrix& operator=(const Matrix& m);
    Matrix& operator+=(Matrix& m);
private:
    int m_ColSize, m_RowSize;
    double  **m_NumArray;
};
[ . . . . ]

Example 19.10. src/operators/matrix/matrix.cpp

#include "matrix.h"

Matrix:: Matrix(int c, int r):m_ColSize(c), m_RowSize(r) {
    m_NumArray = new double*[c];
    for (int i = 0; i < c; ++i) 
        m_NumArray[i] = new double[r];
}