0

I was wondering about how to overload () operator

For example

class A{
    int a,b;
public:
    void operator()(int x, int y);
};

void A::operator()(int x, int y){
    x = a;
    y = b;
}

int main(){
    A a = new A();
    a(5,4); // this will call the overloaded operator
    return 0;
}

I was wondering if there are any other use cases to the following and any other scenario where this can be called.

Mankarse
  • 39,818
  • 11
  • 97
  • 141
manugupt1
  • 2,337
  • 6
  • 31
  • 39
  • 1
    Are you asking for use cases of `operator()` _in general_ (that's a fairly broad question then..), or are you asking about the specific implementation of the operator you gave above, i.e. an operator that uses the arguments as input to set data members? – jogojapan Nov 07 '12 at 02:31
  • When you say _the following_, you mean _the above_, right? – jogojapan Nov 07 '12 at 02:32
  • The overloaded operator can also be called with `a.operator()(5,4)`, if that is what you are asking... – Mankarse Nov 07 '12 at 02:33
  • Actually, I just realised, your operator does not even set data members. It sets local variables `x` and `y` to the values of its data members. That isn't very useful at all. It would become potentially useful if you were to take the arguments as references `operator()(int &x, int &y)`. – jogojapan Nov 07 '12 at 02:33
  • 2
    For general information about the myriad virtues of functors (i.e. classes that overload `operator()`), best see this existing question: http://stackoverflow.com/questions/356950/c-functors-and-their-uses. – jogojapan Nov 07 '12 at 02:37

2 Answers2

3

operator() is just like any other function. The only difference is that instead of calling it like a.foo(), you write a().

You can use it exactly like any other function, you can overload it as much as you want, it can have as many parameters as you want (including zero), it can be templated and anything else that you can think of that any other function can do.

Jarryd
  • 1,312
  • 11
  • 17
0

In general operator() is used to give an object function calling semantics. If your object can be seen as "doing something" then it might make sense to use this operator. These objects are known as functors. They are often used to encapsulate some action that will be done repeatedly especially on many objects.

See the STL headers algorithm and functional for interesting examples and uses.

By the way, you are allocating an A but assigning it to an object instead of a pointer. And you are calling your A::operator() when you are allocating A, and your complier should complain. Change A a = new A() to something like A* a = new A; or simpler A a; since a doesn't need to exist beyond main's execution. If you use the pointer version you have to call operator() like so (*a)(5,4);

Also your A::operator() will have no effect. The x and y arguments are passed by value. Pass them by reference instead.

Jason
  • 1,612
  • 16
  • 23