views:

108

answers:

2

in c++ i have following code

class Foobar{
public:
  Foobar * operator()(){
      return new Foobar;
 };

My quesion is how to call the (); if i do Foobar foo() the constructor gets called i am confused about behaviour of () can some explain me

+4  A: 

Like this:

Foobar f;
Foobar* p = f(); // f() invokes operator()
delete p;

Also this is very weird, in terms of returning a pointer like that and it being a rather useless function. (I "need" a Foobar to make a new one?)

GMan
I would add the qualification that you *should not be doing this*. It's really weird and non-idiomatic to return a `new` instance from `operator()`!
Dean Harding
yeah thats true i was checking something weried
anish
+5  A: 

While GMan's answer is factually correct, you should never overload an operator to do something unexpected - this goes against all good-practice programming rules. When a user reads code he expects operators to behave in some way, and making them behave differently is good only for obfuscating coding competitions.

The () operator in C++ can be used to make an object represent a function. This actually has a name - it's called functor, and is used extensively in the STL to provide generic algorithms. Google for stl functor to learn about a good usage of the technique.

Eli Bendersky
This isn't the only common use of `operator()`. It's also used for chaining. `boost::program_options` demonstrates a good example with its `options_description_easy_init::operator()()` (but client only deal with `options_description::add_option()` which returns the chainable type). You use it to add support for one commandline option after another. It is also common to use `operator<<` and `operator>>` for this same purpose. `std::cout` and `std::cin` are the classic example here. The choice among these three is usually a choice of aesthetics.
wilhelmtell
While you're certainly right about operators in general (don't overload `+` to do `*=`'s work), to me it seems `operator()()` is an exception. It's use is to mimic a function and functions are used to do anything, so there is no conventional limit to what `operator()()` is used to. That makes -1 from me, despite your nice avatar. `:)`
sbi