简体   繁体   中英

C++ Member Functions vs Free Functions

I keep on getting confused about this design decision a lot of the time when I'm writing programs, but I'm not 100% sure when I should make a function to be a member function of a class, when to leave it as a normal function in which other source files can call the function when the function declaration is exposed in a header file. Does the desired access to member variables of a class have to do with the decision most of the time?

The Interface Principle by Herb Sutter

For a class X, all functions, including free functions, that both
(a) "mention" X, and
(b) are "supplied with" X
are logically part of X, because they form part of the interface of X.

For in depth discussion read Namespaces and the Interface Principle by Herb Sutter.

EDIT
Actually, if you want to understand C++ go and read everything what Herb Sutter has written :)

I use classes when I need to maintain state. If a function doesn't need access to maintained state information, then I prefer a free function because it makes testing and code reuse easier.

If I have a bunch of related functionality but don't need to maintain state, then I prefer putting free functions in a namespace.

If something needs to access member variables or some aspect of an instance of the object, then it should be made a method.

If it is closely related to the class, but doesn't need to access any instance specific information, then it should be made a shared function (or class function, or static function depending on what programming language you are dealing with).

Even if it is just a generic function, chances are that you will have more than one of them and that they can be aggregated/organized according to some concept. Then, you can create a class representing that concept, and make them shared functions.

Given the above, I never see any reason to create standalone functions anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM