7/18/2018 - 9:09 PM

Non-member non-friend interfaces

namespace ns
  class foo
      void member()
        // Uses private data
      // Private data
  void non_member(foo obj)
}; <-------------?????
int main()
  ns::foo obj;


Reduce dependencies on internal class details and improve encapsulation.


The foo class, defined on lines 3–13, has a single member function, member (lines 6–9), that requires access to foo’s private data.

The function non_member on lines 15–18 is also logically part of foo’s interface, yet has been defined as a non-member because it can be implemented in terms of member. This approach improves encapsulation by reducing the number of functions that are dependent on the private members of a class.

On line 24, argument-dependent lookup (ADL) allows us to call non_member without qualifying it with the ns namespace. The ADL rule specifies that the name of a function will be looked up in the namespaces of its arguments. As we are passing an ns::foo to non_member, the function is found in the ns namespace.