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?
A function declared/defined within a class is a member function and a function declared/defined outside the scope of a class is a function.
A member function is declared in the class but defined outside the class and is called using the object of the class. A non-member function that is declared outside the class but called a normal function inside the main function.
Member functions are operators and functions that are declared as members of a class. Member functions do not include operators and functions declared with the friend specifier. These are called friends of a class.
The term free function in C++ simply refers to non-member functions. Every function that is not a member function is a free function.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With