When should I prefer non-member non-friend functions to member functions?

后端 未结 4 809
南方客
南方客 2020-12-08 03:27

Meyers mentioned in his book Effective C++ that in certain scenarios non-member non-friend functions are better encapsulated than member functions.

Example:

4条回答
  •  伪装坚强ぢ
    2020-12-08 04:02

    I often choose to build utility methods outside of my classes when they are application specific.

    The application is usually in a different context then the engines doing the work underneath. If we take you example of a web browser, the 3 clear methods belongs to the web engine as this is needed functionality that would be difficult to implement anywhere else, however, the ClearEverything() is definitely more application specific. In this instance your application might have a small dialog that has a clear all button to help the user be more efficient. Maybe this is not something another application re-using your web browser engine would want to do and therefor having it in the engine class would just be more clutter.

    Another example is a in a mathematic libraries. Often it make sense to have more advanced functionality like mean value or standard derivation implemented as part of a mathematical class. However, if you have an application specific way to calculate some type of mean that is not the standard version, it should probably be outside of your class and part of a utility library specific to you application.

    I have never been a big fan of strong hardcoded rules to implement things in one way or another, it’s often a matter of ideology and principles.

    M.

提交回复
热议问题