Re: Point of operator() overloading (no pun intended)
"Stick" <Stick@discussions.microsoft.com> wrote in message
news:6429B63C-3FE5-4B6A-81DB-B94836C841AC@microsoft.com
"David Wilkinson" wrote:
The point is to offset an existing Point. You would need a
4-parameter constructor to do this. Personally, I do not like using
operator () to do this; I would prefer operator +=.
David,
Yes, I realize the purpose of the above was to offset the point's
coordinats, and I agree overloading += would be better.
I just don't get why you need operator() overloading.
It just seems like there is nothing really gained by it, as the
syntax just looks like a constructor, yet, you could easily just have
a member function do something.
In addition to the examples that Igor and Carl have given, the following
general description of the advantages of function objects (largely taken
from Josuttis, The C++ Standard Library, p.127) may be helpful:
1. They can store information in member variables ("retain state") between
successive calls. A function can also do that by use of static variables,
but there can only be one set of static variables for a function and hence
only one "state" can be retained. By contrast, since each functor is a class
object, you can have as many such objects as you like. Moreoever, each
functor's state can be initialized via its constructor (see Igor's example).
Functions don't offer the same initialization possibilities.
2. Each function object has its own type. By contrast all functions that,
say, take an int argument and return a double have the same type. This means
that you can pass the class of a function object as a template parameter.
You can't do that with functions. This is a great advantage in template
programming. The classes associated with function objects can also be
organised into inheritance heirarchies, which creates added flexibility that
functions lack.
3. Function objects often offer better performance. Thus if a sorting
function object is passed to a container, then you may get better
performance than if a sorting function is passed to a container, since more
details can be defined at compile time (given that, as per 2., each function
object has its own type).
--
John Carson