I keep hearing a lot about functors in C++. Can someone give me an overview as to what they are and in what cases they would be useful?
For the newbies like me among us: after a little research I figured out what the code jalf posted did.
A functor is a class or struct object which can be "called" like a function. This is made possible by overloading the () operator
. The () operator
(not sure what its called) can take any number of arguments. Other operators only take two i.e. the + operator
can only take two values (one on each side of the operator) and return whatever value you have overloaded it for. You can fit any number of arguments inside a () operator
which is what gives it its flexibility.
To create a functor first you create your class. Then you create a constructor to the class with a parameter of your choice of type and name. This is followed in the same statement by an initializer list (which uses a single colon operator, something I was also new to) which constructs the class member objects with the previously declared parameter to the constructor. Then the () operator
is overloaded. Finally you declare the private objects of the class or struct you have created.
My code (I found jalf's variable names confusing)
class myFunctor
{
public:
/* myFunctor is the constructor. parameterVar is the parameter passed to
the constructor. : is the initializer list operator. myObject is the
private member object of the myFunctor class. parameterVar is passed
to the () operator which takes it and adds it to myObject in the
overloaded () operator function. */
myFunctor (int parameterVar) : myObject( parameterVar ) {}
/* the "operator" word is a keyword which indicates this function is an
overloaded operator function. The () following this just tells the
compiler that () is the operator being overloaded. Following that is
the parameter for the overloaded operator. This parameter is actually
the argument "parameterVar" passed by the constructor we just wrote.
The last part of this statement is the overloaded operators body
which adds the parameter passed to the member object. */
int operator() (int myArgument) { return myObject + myArgument; }
private:
int myObject; //Our private member object.
};
If any of this is inaccurate or just plain wrong feel free to correct me!