C++ Strategy pattern

In my opinion, implementation of strategy pattern using function pointers is done in languages which don't have support for OOP (such as C).

In languages which support OOP, its better implemented using classes : inheritance, virtual functions (i.e runtime polymorphism), interface, and so on. Usually, this is runtime strategy pattern which means, you can change the behavior of the program just by switching to other strategy pattern, at runtime.

In C++, there is also a compile-time strategy pattern, commonly known as policy-based design.

In any case, classes can maintain states, while function pointers cannot. That is the biggest advantage in using classes.


You simply have to use inheritance in languages without function pointers (read: Java).

Personally, I would prefer std::function over raw function pointers, because it accepts a wider range of arguments and allows you to maintain state in the strategy object.

Also, if you already know the strategy at compile-time, you can even use templates and thus save both the space and runtime overhead of function pointers and std::function objects.