0

I'm trying to understand operator overloading in C++, and can see the usefulness when used carefully on operators like + and []. I'm interested now in the overloading of (). Boost seems to use it with its statistical classes, and I can use them, but don't really understand what I'm doing.

Can anyone provide a simple example of when overloading the () operator would be useful? Thanks guys Pete

Pete855217
  • 1,570
  • 5
  • 23
  • 35
  • It's a key part of `std::function` in order to call the contained function like you would normally. – chris Jun 09 '12 at 05:17
  • 8
    The term you probably want to search for is "Functor". – Jerry Coffin Jun 09 '12 at 05:17
  • I did do a google search, but the examples I found seem very focussed on other operators. – Pete855217 Jun 09 '12 at 05:17
  • Thanks Jerry - that's brought up lots more specific examples. Here's a good one I'm studying: http://www.learncpp.com/cpp-tutorial/99-overloading-the-parenthesis-operator/ – Pete855217 Jun 09 '12 at 05:18
  • @Pete855217 No, it is not a good example (the link you have provided). It teaches you how to overload but the use-case is not that common. – Hindol Jun 09 '12 at 05:23
  • http://stackoverflow.com/questions/356950/c-functors-and-their-uses gives a good explanation of functors. – Josh Townzen Jun 09 '12 at 05:57
  • Thanks Josh - now I know () is a functor, the whole thing makes alot more sense. The example in learncpp is great for a real-life (well as real-life as code can be) sample. – Pete855217 Jun 12 '12 at 08:58

2 Answers2

1

A common use of overloading the operator() is for function objects or functors. You can use objects of a class that defines the operator() and use as if it is a function as shown in example below:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class multiply
{
private:
    int x;
public:
    multiply(int value):x(value) { }
    int operator()(int y) { return x * y; }
    int getValue() { return x; }
};

int main()
{
    multiply m(10); //create an object
    cout << "old value is " << m.getValue() << endl;
    int newValue = m(2); //this will call the overloaded () 
    cout << "new value is " << newValue << endl;
}
Sanish
  • 1,699
  • 1
  • 12
  • 21
  • Thanks Sanish - the second last line is the nub of the matter, makes sense although I can see overloading () can be problematic as there's nothing in the code that actually tells you what using () might do. – Pete855217 Jun 12 '12 at 09:00
0

Summary: Overloading the () operator in a C++ class lets you implement class methods with different types and numbers of parameters, providing different functionality for each. Care is required when overloading () as its usage provides no clues as to what's being done. It finds limited use, but can be effective for things like matrix manipulation.

From: Overloading the () operator (learncpp.com)

Pete855217
  • 1,570
  • 5
  • 23
  • 35