Do non-member non-friend functions really increase encapsulation?

Meyers does not say avoid member functions. He says that functions should not be members (or friends) unless they need to be. Obviously there need to be some functions which can access the private members of a class otherwise how could any other code interact with the class, right?

But every function which can access the private members of a class is coupled to the private implementation details of that class. The functions which should be members (or friends) are the ones which can only be efficiently implemented by accessing the private details. These are the primitive functions of a class. Non-primitive functions are those which can be efficiently implemented on top of the primitive ones. Making non-primitive functions members (or friends) increases the amount of code which is coupled to the private details.

Also, in writing a function which is able to modify the private members of an object, more care must be taken in order to preserve the class invariants.


Meyers gives his reasoning in this article. Here's an extract:

We've now seen that a reasonable way to gauge the amount of encapsulation in a class is to count the number of functions that might be broken if the class's implementation changes. That being the case, it becomes clear that a class with n member functions is more encapsulated than a class with n+1 member functions. And that observation is what justifies my argument for preferring non-member non-friend functions to member functions: if a function f could be implemented as a member function or as a non-friend non-member function, making it a member would decrease encapsulation, while making it a non-member wouldn't.

Tags:

C++