Arun Arun - 21 days ago 6
C++ Question

A class with static methods or class with normal methods

I have a utility class which doesn't hold any data members and just provides some services through its methods. In such a case what approach is better, create a class with all static methods or create a class with normal methods and call them by creating an object of the class? What are the pros and cons of either of the approaches?

Answer

I think the superior choice is using a namespace and free functions. Reasons:

  • Using a class with normal methods is confusing, as it needs to be instantiated but has no state.

  • Using a class with only static methods is better, but requires the user to always specify the name of the class.

  • Using a namespace and free functions prevents the possibility of confusing/unnecessary instantiations, and also allows the user to alias the namespace or use using namespace to avoid repetition when using multiple functions in the same scope. The namespace can also span multiple files.