Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL

Class Design and Inheritance > Prefer writing nonmember nonfriend functions - Pg. 79

Class Design and Inheritance 79 44. Prefer writing nonmember nonfriend functions. Summary Avoid membership fees: Where possible, prefer making functions nonmember non- friends. Discussion Nonmember nonfriend functions improve encapsulation by minimizing dependen- cies: The body of the function cannot come to depend on the nonpublic members of the class (see Item 11). They also break apart monolithic classes to liberate separable functionality, further reducing coupling (see Item 33). They improve genericity, be- cause it's hard to write templates that don't know whether or not an operation is a member for a given type (see Item 67). Use this algorithm to determine whether a function should be a member and/or friend: // If you have no choice then you have no choice; make it a member if it must be: If the function is one of the operators =, ->, [], or (), which must be members: Make it a member. // If it can be a nonmember nonfriend, or benefits from being a nonmember friend, do it: Else if: a) the function needs a different type as its left-hand argument (as do op- erators >> or <<, for example); or b) it needs type conversions on its leftmost argument; or c) it can be implemented using the class's public interface alone: Make it a nonmember (and friend if needed in cases a) and b) ). If it needs to behave virtually: Add a virtual member function to provide the virtual behavior, and im- plement the nonmember in terms of that. Else: Make it a member. Examples Example: basic_string. The standard basic_string is a needlessly monolithic class with 103 member functions--of which 71 could be written as nonmember nonfriends without loss of efficiency. Many of them duplicate functionality already available as algorithms, or are themselves algorithms that would be useful more widely if they weren't buried inside basic_string. (See Items 5 and 32, and [Sutter04].) References [Lakos96] §3.6.1, §9.1.2 · [McConnell93] §5.1-4 · [Murray93] §2.6 · [Meyers00] · [Stroustrup00] §10.3.2, §11.3.2, §11.3.5, §11.5.2, § · [Sutter00] §20 · [Sutter04] §37-40