Nayana Adassuriya
Nayana Adassuriya

Reputation: 24766

Use of operator ()

I have few question about () operator. Please help me to get clear idea.

  1. What is the use of () operator (() operator overloading).
  2. In which situations it should use.
  3. What are the practical example of () operator usage (in which situations that useful,convenient or suitable to use () operator ).

Upvotes: 0

Views: 123

Answers (2)

Josh Engelsma
Josh Engelsma

Reputation: 2646

The () operator is used to make what is known as a function object aka "functor"

There are some very interesting things that having a function object allows one to do including passing a function object as a parameter.

The link I am posting below is a video from a class I was taking where the professor is talking about functors. I find it very helpful. (Note: the vid also talks about class templates)

Functors and Templates

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385088

It's primarily used in function objects to simulate function calls.

#include <iostream>

struct Functor
{
   void operator()() {
      std::cout << "lol\n";
   }
};

int main()
{
   Functor f;
   f();  // output: "lol"
}

Live demo

A contrived example, yes, but this gets more complex with constructor arguments and when, say, storing this functor for use in an algorithm. It's very common in the C++ standard library.


You don't have to use it in this way; another example is simulating multi-dimensional array access:

#include <vector>

template<typename T>
struct Matrix
{
   Matrix(unsigned m, unsigned n)
      : m(m), n(n), vs(m*n) {}

   T& operator()(unsigned i, unsigned j)
   {
      return vs[i + m * j];
   }

private:
   unsigned m;
   unsigned n;
   std::vector<T> vs;

};

/**    
 *       _~
 *    _~ )_)_~
 *    )_))_))_)
 *    _!__!__!_
 *    \______t/
 *  ~~~~~~~~~~~~~
 */
int main()
{
   const unsigned int WIDTH = 3;
   const unsigned int HEIGHT = 3;

   Matrix<long> m(WIDTH, HEIGHT);
   m(1,1) = 42;
}

This one is useful because operator[] may take only one parameter (though that parameter can be an initializer list, which is a workaround).

Upvotes: 5

Related Questions