Function objects are simple but don’t let that fool you. You can use them in clever solutions.

It’s more difficult to explain why you might want to use a function object if you don’t yet know what a function object is. So that’s mostly what this episode explains. What is a function object? They’re sometimes called functors for short.

In many ways, you can think of a functor as a more complicated way to write a method. That’s what I hope to explain because there are some unique benefits to writing a method in the form of a function object.

Alright, a method has a signature. Let’s say you have a method that can add two integers. How would you write this as a functor?

class add
	add() {}

	int operator () (int first, int second)
		return first + second;

The big question now is why? What possible benefit could come from such a roundabout and complicated way of writing a method? Well, if this is all the functor was going to do, then I’d agree. You should just use a method. But you have a class now and that means it can have other class member variables that control it’s behavior.

The only way to change the behavior of a method is to pass in different arguments. But with a functor, you can construct the class with whatever information you want and even call other methods that can change or modify internal data members. Then when you want to use it as if it was a function, it can refer to its own internal data to do different things.