Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Let's talk about operator +. Having it as a non member allows code such as the following</p> <pre><code>string s1 = "Hi"; string s2 = "There"; string s3; s3 = s1 + s2; s3 = s1 + "Hi"; s3 = "Hi" + s1; </code></pre> <p>The last assignment statement is not possible if operator+ is a member rather than a namespace scope function. But if it is a namespace scope function, the string literal "Hi" is converted into a temporary string object using the converting constructor "string(const char *);" and passed to operator+.</p> <p>In your case, it was possible to manage without making this function a friend as you have accessors for the private member 'buf'. But usually, if such accessors are not provided for whatever reason, these namespace scope functions need to be declared as friends.</p> <p>Let's now talk about operator &lt;&lt;.</p> <p>This is the insertion operator defined for ostream objects. If they have to print objects of a user defined type, then the ostream class definition needs to be modified, which is not recommended.</p> <p>Therefore, the operator is overloaded in the namespace scope.</p> <p>In both the cases, there is a well known principle of <a href="http://en.wikipedia.org/wiki/Argument-dependent_name_lookup" rel="nofollow">Argument Dependent Lookup</a> that is the core reason behind the lookup of these namespace scope functions, also called Koenig Lookup.</p> <p>Another interesting read is the <a href="http://www.gotw.ca/publications/mill08.htm" rel="nofollow">Namespace Interface Principle</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload