Non-member non-friend interfaces
12345678910111213141516171819202122232425 | namespace ns
{
class foo
{
public:
void member()
{
// Uses private data
}
private:
// Private data
};
void non_member(foo obj)
{
obj.member();
}
}
int main()
{
ns::foo obj;
non_member(obj);
} |
This pattern is licensed under the CC0 Public Domain Dedication.
Intent
Reduce dependencies on internal class details and improve encapsulation.
Description
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.