    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Overloading Operators</title>
        <link>https://members.accu.org/index.php/articles/549</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #30 - Feb 1999</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c174/">30</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-174/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+174/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Overloading Operators</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 February 1999 16:50:51 +00:00 or Fri, 26 February 1999 16:50:51 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e14" id="d0e14"></a></h2>
</div>
<p>We can very loosely separate operators into three groups.</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>Operators like the comparison operators, logical operators etc.
that do not modify their operands and return a type that is
unrelated to the type of the operands.</p>
</li>
<li>
<p>Operators that modify their left-hand operand (by convention)
These include the assignment operators (including the compound
ones)</p>
</li>
<li>
<p>Operators that conceptually return a value of the same type as
the right-hand operand. The traditional arithmetic operators are
the prime examples of these.</p>
</li>
</ol>
</div>
<p>For now I want to focus on ideas for implementing that last
group.</p>
<p>The traditional, and I believe poor, design is to provide these
operators as friends of the relevant class. There are times when
the friendship is required for implementing some operators
efficiently. The major indicator of these is that the left and
right operand will be of different user-defined types. For example
multiplying a matrix by a vector (in mathematical terms). However
there is usually a better solution.</p>
<p>First note that arithmetic operators would only normally be
applied to value types (ones that support public copying and so can
be passed and returned by value). This is important because it
means we can expect an accessible copy constructor.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e34" id="d0e34"></a>Conventional
Solution</h2>
</div>
<p>Let me restrict myself to addition (+). Almost everything that I
write will be equally applicable to other arithmetic operations.
Note that a type can support multiple overloads of addition (i.e.
add together two instances of the same type, add an instance of one
type to an instance of another type).</p>
<p>The conventional solution is to provide an in-class operator+=
and then use that to provide an out of class (i.e. namespace scope)
operator+. For example:</p>
<pre class="programlisting">
class Rational
{
  // lots of interface detail
public:
  Rational &amp; operator+=(Rational &amp; const rhs);
};
inline Rational operator+
(Rational const &amp; lhs, Rational const &amp; rhs)
{
  return Rational(lhs) += rhs;
}
</pre>
<p>This form (which may be new to you) creates an anonymous
Rational as a copy of the lhs and then modifies it by adding the
rhs. The resulting value is nominally returned by copying to the
return value. However, compilers with a respectable level of
optimisation will elide that copy and use the location of the
return value for the anonymous temporary.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e45" id="d0e45"></a>Alternative
Solutions</h2>
</div>
<p>Some programmers find the idea of creating overloads for the
compound assignment operators distasteful and so are tempted to
resort to using friend declarations to get around the problem.
There is no reason why they should do this.</p>
<p>First there is the simple solution of providing an in class
'add' function. Our code now looks like this:</p>
<pre class="programlisting">
class Rational 
{
  // lots of interface detail
public:
  Rational add(Rational &amp; const rhs) const;
};

inline Rational operator+
(Rational const &amp; lhs, Rational const &amp; rhs)
{
  return lhs.add(rhs);
}
</pre>
<p>The next issue that gets raised is that technically this results
in two calls of the copy constructor, one to return from the add
function by value, and the second to return that value from the
operator+ wrapper. It would be a pretty poor compiler that did this
(so I guess there are still a few poor compilers around). However,
if you are really unhappy then notice that what an addition
operation does is to create a new value from two existing ones.
Does that suggest anything? What about using a constructor?</p>
<p>So here is a third design.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e58" id="d0e58"></a>Operator
Constructors</h2>
</div>
<pre class="programlisting">
class Rational 
{
// lots of interface detail
public:
  Rational
   (Rational &amp; const lhs, Rational const rhs);
};
inline Rational operator+
(Rational const &amp; lhs, Rational const &amp; rhs)
{
  return Rational(lhs, rhs);
}
</pre>
<p>Conceptually this is probably the cleanest solution but it has a
drawback. How am I going to provide constructor operators for the
other arithmetic operations? It doesn't take long to realise that
we need another parameter whose type will determine which operator
is being supported. If we want a static (compile time) decision
this third parameter must be of a different type for each of the
operators. (You can avoid this by using an enum and having an
internal switch statement, but that is clumsy and probably makes it
harder for the compiler to optimise your code).</p>
<p>I want to be able to provide a set of constructors such as:</p>
<pre class="programlisting">
Rational(lhs, rhs, Add);
Rational(lhs, rhs, Subtract);
Rational(lhs, rhs, Multiply);
Rational(lhs, rhs, Divide);
</pre>
<p>With Add, Subtract, Multiply and Divide being distinct
types.</p>
<p>Fine, but where should these extra UDT go? Once I decide to use
this mechanism to provide arithmetic operators I might as well
generalise. So rather than place the definitions inside the
Rational class, or inside the enclosing namespace I think it makes
sense to provide:</p>
<pre class="programlisting">
namespace Operators
{
  struct Add {};
  struct Subtract{};
  struct Multiply{};
  struct Divide{};
  // and any other operators that you think
  // you want to provide via constructors.
}
</pre>
<p>(Note that C++ does not support a semicolon after the closing
brace of a namespace. I hope this was just a mistake and not a
deliberate decision of the Standards Committees. If it was the
latter I would dearly like to hear the rational supporting the
decision)</p>
<p>Interestingly, this is yet another example of empty,
functionless classes being useful.</p>
<p>With the above in place we can now write:</p>
<pre class="programlisting">
    Using namespace Operators;
</pre>
<p>as a using directive inside the namespace in which we define our
class Rational. I think that is a perfectly sensible way to use a
using directive. Now we can provide our overloaded arithmetic
operators with:</p>
<pre class="programlisting">
inline Rational operator+
(Rational const &amp; lhs, Rational const &amp; rhs)
{
  return Rational(lhs, rhs, Add());
}
</pre>
<p>[and similarly for the other operators]</p>
<p>A good compiler will generate no code for that anonymous
instance of an empty class, just use its type to discriminate
between the different operators.</p>
<p>Once you get the hang of this idea you might be tempted to write
the following template function:</p>
<pre class="programlisting">
template&lt;typename T&gt; inline T operator+
(T const &amp; lhs, T const &amp; rhs)
{
  return T(lhs, rhs, Add());
}
</pre>
<p>Resist the temptation. The main reason that you do not use a
member function for operator+ is because you want to allow
symmetric conversions to type T. Providing a template is the best
way of torpedoing this intent that I know. There are many
opportunities for using templates but this is not one of them.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e97" id="d0e97"></a>Disambiguating
Declarations</h2>
</div>
<p>You do not have to program very long in C++ before you come
across the problem exemplified by the following code:</p>
<pre class="programlisting">
int main()
{
  Mytype mt1(3);
  Mytype mt2();
  // other code
};
</pre>
<p>The first declaration declares an instance of <tt class=
"classname">Mytype</tt> that is constructed with a constructor that
takes a single parameter that can accept an argument of type
<tt class="type">int</tt>. The na&iuml;ve programmer thinks the
second declaration should create an instance by using the default
constructor for <tt class="classname">Mytype</tt>. However there is
an alternative way of viewing that line. It is also a prototype for
a function mt2 that returns a <tt class="classname">Mytype</tt> by
value and has no parameters.</p>
<p>As all experienced programmers know, this is resolved in favour
of its being a prototype. If that were not the case you would have
some difficulty in declaring such a prototype. C++ would then have
required empty parameter lists to be specified with void as they
are in C. That might have been OK had it not been that a general
disambiguation rule was required anyway. For example:</p>
<pre class="programlisting">
enum X {zero, one, ten=10};
class Mytype
{
// a ctor that takes an X parameter
  Mytype(X);
};

int main ()
{
  int i=3;
  Mytype mt(X(i));
  // other code
}
</pre>
<p>and now we have that ambiguity again. This time because the
ancestral language, C, allow redundant parentheses. <tt class=
"literal">Mytype mt(X(i))</tt> is the same as <tt class=
"literal">Mytype mt(X i)</tt>.</p>
<p>Rather than have a raft of special disambiguation rules C++
makes do with one: if a declaration can be a function prototype, it
is a function prototype.</p>
<p>Unfortunately, this results in traps lying around for the
unwary. However, I wonder about the following variation:</p>
<pre class="programlisting">
int main () 
{
  int i=3;
  auto Mytype mt(X(i));
  // other code
}
</pre>
<p>I do not believe that you can prototype a function as returning
an <tt class="literal">auto</tt> (or come to that, a <tt class=
"literal">register</tt>) qualified type. Therefore, I believe that
the otherwise useless keyword <tt class="literal">auto</tt> should
disambiguate declarations in favour of objects over functions.
However, when I tried this on a couple of compilers they seemed to
want to complain about the <tt class="literal">auto</tt>. Which of
us is right?</p>
<p>I hope I am because it would be nice to provide a simple fix to
force the selection you want without having to know all the special
solutions that are currently required.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
