57. Keep a type and its nonmember function interface in the same namespace

Summary

Nonmembers are functions too: Nonmember functions that are designed to be part of the interface of a class X (notably operators and helper functions) must be defined in the same namespace as the X in order to be called correctly.

Discussion

Both public member functions and nonmember functions form part of the public interface of a class. The Interface Principle states: For a class X, all functions (including nonmember functions) that both “mention” X and are “supplied with” X in the same namespace are logically part of X, because they form part of X’s interface. (See Item 44 and [Sutter00].)

The C++ language is explicitly designed to enforce the Interface Principle. ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.