Free function versus member function

Jana picture Jana · Jan 9, 2014 · Viewed 18.3k times · Source

What is the advantage of having a free function (in anonymous namespace and accessible only in a single source file) and sending all variables as parameters as opposed to having a private class member function free of any parameters and accessing member variables directly?

header:

 Class A {
    int myVariable;
    void DoSomething() {
       myVariable = 1;
    }
 };

source:

 namespace {
    void DoSomething2(int &a) {
        a = 1;
    }
 }

 int A::SomeFunction() {
    DoSomething2(myVariable); // calling free function
    DoSomething(); // calling member function
 }

If you prefer making them members, then what if I have a case where I first call a function that is not accessing any member variables, but that function calls another function which is accessing a member. Should they both be member functions or free?

Answer

Stephane Rolland picture Stephane Rolland · Jan 9, 2014

see this question: Effective C++ Item 23 Prefer non-member non-friend functions to member functions and also C++ Member Functions vs Free Functions

You should prefer free functions, in the extent that it promotes loose coupling.

Consider making it a member function only if it works on the guts of your class, and that you consider it really really tied to your class.

It is a point of the book 101 C++ coding standards, which states to prefer free function and static function over member functions.

Altough this may be considered opinion based, it allows to keep class little, and to seperate concerns.

This answer states: "the reason for this rule is that by using member functions you may rely too much on the internals of a class by accident."