anish
anish

Reputation: 1033

how to call operator () in c++

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

Upvotes: 0

Views: 345

Answers (2)

Eli Bendersky
Eli Bendersky

Reputation: 273366

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.

Upvotes: 5

GManNickG
GManNickG

Reputation: 503775

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?)

Upvotes: 5

Related Questions