Search code examples
c++classoverloadingparentheses

What does overloading the parentheses operator do?


I see this very often and I'm wondering what it does/its purpose.

  1. What does overloading operator() do?
  2. Why do people usually overload this operator?

Example

std::vector<double> operator()(int seed) const;

Thanks!


Solution

  • Functors and matrix indexing are, to my knowledge, the most common use cases.

    Matrix Indexing
    For a matrix class, you can do something like this:

    Matrix3x3 A;
    A(1,2) = 2;
    

    The main reason that parentheses are used instead of brackets in this case is that the brackets operator only accepts one argument while the parentheses operator accepts multiple arguments.

    Functor
    If you want an object to act as a function that can also store information, you can do:

    Accumulator accumulate;
    for(int i=0; i<20; ++i)
        accumulate(i);
    std::cout << accumulate.sum << std::endl;
    

    In C++, you will also often encounter functors for comparator objects, even though they do not store information.