\documentstyle[12pt]{article}
\oddsidemargin 0.25in
\topmargin -0.5in
\textheight 8.5in
\textwidth 6.25in
\newcommand{\doublespace}{
   \renewcommand{\baselinestretch}{1.5}
   \large\normalsize}
\newcommand{\singlespace}{
   \renewcommand{\baselinestretch}{1.0}
   \large\normalsize}
\newcommand{\be}{\begin{equation}}
\newcommand{\ee}{\end{equation}}

\begin{document}
\setcounter{page}{65}

\centerline{\large{\bf LECTURE 7}}

\centerline{\bf Overloading Operators Continued}
If an operator for a built--in type has a certain number of arguments,
you can't overload it with a different number of arguments.
For example, you can't make a unary operator binary or a binary operator
(like +) ternary. In addition, if you overload the addition operator
for some class {\tt Z} (\verb2Z::operator+()2) and the assignment
operator (\verb2Z::operator=()2), the compiler will not generate a 
definition of \verb2Z::operator+=()2. Each operator
must be overloaded independently. I want to talk about overloading
a few other operators.

\centerline{\bf Overloading the Prefix and Postfix Operators}
Suppose we have a class {\tt USDollar} which has an integer number
of dollars and an integer number of cents less than 100. The class
declaration might look something like:
\begin{verbatim}
  class USDollar
    {
      friend USDollar operator+(USDollar&, USDollar&);
      friend USDollar& operator++(USDollar&);
      public:
       USDollar(unsigned int d, unsigned int c);
      private:
       unsigned int dollars;
       unsigned int cents;
    };
\end{verbatim}
The \verb2operator++()2 increments the cents field. If it goes over
100, it increments the dollar field and zeros out the cents.
This operator returns a reference to {\tt USDollar} because it
changes the value of the provided object.
\begin{verbatim}
   USDollar& operator++(USDollar &s)
     {
      s.cents++;
      if (s.cents >=100)
      {
         s.cents -= 100;
         s.dollars++;
      }
      return s;
     }
\end{verbatim}
If you want to overload the prefix operator \verb2++x2 separately
from the postfix version \verb2x++2, here is the rule. 
\verb2operator++(ClassName)2 refers to the prefix operator and \\
\verb2operator++(ClassName,int)2 refers to the postfix operator. 
The {\tt int} is never used; the argument is simply a dummy used
to distinguish between prefix and postfix applications. The same
rule applies to \verb2operator--()2. If you only provide one
\verb2operator++()2 or \verb2operator--()2, most compilers will
use it for both the prefix and postfix versions. 

\centerline{\bf Cast Operator}
The cast operator can be overloaded as well. Let's take an example
from {\it C++ for Dummies}.
\begin{verbatim}
   class USDollar
   {
   public:
     USDollar(double value = 0.0);    //constructor with default value
     //the following function acts as a cast operator
     operator double()
     {
       return dollars + cents / 100.0;
     }
   private:
     unsigned int dollars;
     unsigned int cents;
    };
   USDollar::USDollar(double value)  //constructor
    {
     dollars = (int)value;
     cents = (int)((value - dollars) * 100 + 0.5);
    }
   int main()
    {
     USDollar d1(2.0), d2(1.5), d3;
     //invoke cast operator explicitly... 
     d3 = USDollar((double)d1 + (double)d2);  
     //...or implicitly
     d3 = d1 + d2;
     return 0;
    }
\end{verbatim}
A cast operator is the word {\tt operator} followed by the desired type.
The member function \verb2USDollar::operator double()2 provides a
mechanism for converting an object of class {\tt USDollar} into a
{\tt double}. Cast operators have no return type. As the preceding
example shows, conversions using the cast operator can be invoked
either explicitly or implicitly. Look at the implicit case carefully.

In trying to make sense of the expression \verb4d3 = d1 + d24,
C++ first looked for member function \verb4USDollar::operator+(USDollar)4.
When that wasn't found, it looked for the non--member version
\verb4operator+(USDollar,USDollar)4. Lacking that as well, it 
started looking for an \verb4operator+()4 that it could use by
converting one or the other arguments into a different type. 
Finally it found a match: by converting both {\tt d1} and 
{\tt d2} to {\tt double}s, it could use the intrinsic 
\verb2operator+(double, double)2. It then has to convert the resulting
{\tt double} back to {\tt USDollar} using the constructor.

This demonstrates both the advantage and disadvantage of providing
a cast operator. Providing a conversion path from {\tt USDollar} to
{\tt double} relieves programmers of the need to provide their own
set of operators. {\tt USDollar} can just piggyback on the operators
defined for {\tt double}. 

On the other hand, it also removes the ability of the programmer to
control which operators are defined. By providing a conversion path
to {\tt double}, {\tt USDollar} gets all of {\tt double}'s operators
whether they make sense or not. In addition, going through the
extra conversions may not be the most efficient process in the
world. For example, the simple addition just noted involves 3
type conversions with all of the attendant function calls, 
multiplications, divisions, and so on.

Be careful not to provide 2 conversion paths to the same type. This
confuses the compiler.
 
\centerline{\bf Overloading Function Call}
The function call operator can be overloaded. This typically takes
the form \verb2operator()()2 or \verb2operator()(arguments)2.
These overloaded operators must be member functions. The first
pair of parentheses represents the class name. The arguments go
inside the second pair of parentheses. For example:
\begin{verbatim}
  #include <iostream.h>
  #include <math.h>

  class Distance{
    private:
     double xc, yc;
    public:
     Distance(double x, double y)        //constructor
      {xc=x;
       yc=y;}
     double operator()()                 //returns a double
       {return sqrt(xc*xc+yc*yc);}

     double operator()(double x)         //returns a double
      {xc=x;                             //reset xc
       return (*this)();}                //use definition of operator ()()
   };

   main()
     { 
      double xx, yy;
      cin >> xx >> yy;
      Distance d(xx,yy);                          //call constructor
      double oldlength=d();                       //call operator ()()
      xx=5.0;                                     //reset xx
      double newlength=d(xx);                     //call operator ()(double x)
      cout << oldlength << " " << newlength<<endl;
     }
\end{verbatim}
Notice that overloading the function call operator has the form
\verb2double operator()()2 or \verb2double operator()(arguments)2 while the
cast operator has the form \verb2operator double()2. Remember that the
cast operator has no return type.

\centerline{\bf Type Conversion Using Constructors}
C++ can use class constructors to convert an object from one type
to another. It will attempt to do this any time it can. However,
it can only use constructors with only a single argument (or with
all arguments defaulted except for one). This is because of syntax
more than anything. Consider the following example:
\begin{verbatim}
#include <iostream.h>

class Number
  {
   public:
    Number(double x)      //constructor
    {xc=x;}
   private:
    double xc;
  };
void func(Number N)      
  {cout << "In function" << endl;}
main()
  {
   double x;
   cin >> x;
   func(x);
  }
\end{verbatim}
{\tt func} is defined to take an argument that is a {\tt Number}.
However, in {\tt main} {\tt func(x)} is called with an
argument that is a {\tt double}. So C++ tries to convert the argument
to a {\tt Number}. It notices that the constructor for {\tt Number}
essentially converts a {\tt double} into a {\tt Number}. So it uses
the constructor to do the type conversion. If ambiguities arise,
the compiler will generate an error. For example,
\begin{verbatim}
#include <iostream.h>

class Number
  {
   public:
    Number(double x)      //constructor
    {xc=x;}
   private:
    double xc;
  };

class AnotherNumber
  {
   public:
    AnotherNumber(double x)      //constructor
    {xc=x;}
   private:
    double xc;
  };
void func(Number N)
  {cout << "In function 1" << endl;}
void func(AnotherNumber N)
  {cout << "In function 2" << endl;}
main()
  {
   double x;
   cin >> x;
   func(x);
  }
\end{verbatim}
To implement {\tt func(x)} C++ could convert {\tt x} to a {\tt Number}
and use {\tt func(Number N)}, or to {\tt AnotherNumber} and use
{\tt func(AnotherNumber N)}. With no way to resolve the ambiguity,
the compiler won't compile the program. To resolve the ambiguity,
we add an explicit call to the intended constructor:
\begin{verbatim}
main()
  {
   double x;
   cin >> x;
   func(Number(x));
  }
\end{verbatim}
Notice how the preceding call to the constructor is similar to a cast.
Here we have cast a {\tt double} to a {\tt Number}. The similarity
is more than superficial. C++ allows this format for specifying a cast.
This new format can also be used for intrinsic casts, plus the old format 
can be used for constructor conversions, as shown in the following:
\begin{verbatim}
  void fn(int *pI)
  {
    float x = 10.5;
    int i = int(x);                  //same as i = (int)x;
    func(Number(x));                 //new format for a cast
    func((Number)x);                 //old format for a cast
    double *pD = (double*)pI;        //older format must be used when 
                                     //casting pointers
  }
\end{verbatim}
Either format is fine. However, you must use the older format when
casting from one pointer type to another due to the syntactical
confusion that \verb2*2 by itself would cause.
Note that a constructor cannot specify an implicit conversion from a
user--defined type to a basic type because the basic types are not
classes. An overloaded cast operator must be used in this case.	

The following rules are very good ideas:
\begin{enumerate}
\item Don't make a cast operator and a constructor that do the 
same jobs. It will confuse the compiler.
\item Don't make more conversion operators than necessary.
\end{enumerate}

\centerline{\bf Boolean Class}
As an example of using constructors to do type conversion, Barton and
Nackman introduce the Boolean class on pages 151--153. Boolean constants
are true or false. The class is defined as follows:
\begin{verbatim}
//This is the Boolean.h file.
#ifndef BOOLEANH
#define BOOLEANH

class Boolean{
public:

// Constants
    enum constants{ False = 0, True = 1 };  //writing "false" or "true"
                                            //will clash with built-in types.

// Constructors used for type conversion.
    Boolean()                      {}   // Uninitialized.
    Boolean(int i) :    v(i != 0)  {}   // Initialize v to (i != 0).
    Boolean(float f) :  v(f != 0)  {}   // Initialize v to (f != 0).
    Boolean(double d) : v(d != 0)  {}   // Initialize v to (d != 0).
    Boolean(void* p) :  v(p != 0)  {}   // Initialize v to (p != 0).

// Overloading cast operator to convert Boolean to int.
    operator int() const{ return v; }   // To allow "if (boolean-value)..."

// Overloading negation operator.
    Boolean operator!() const { return !v; }
private:
    char v;
};

#endif
\end{verbatim}
We use {\tt char v} in order to store 0(false) and 1(true) in the
smallest amount of space in memory. Each of the
single argument constructors defines a conversion from a 
built--in type to a {\tt Boolean}. The {\tt Boolean} object
created is initialized to true if the constructor argument
is nonzero and to false otherwise. A \verb2void*2 is a pointer
to an object of unknown type; any pointer can be converted automatically
to a \verb2void*2 in a manner that converts a null pointer to a null
\verb2void*2  and a non--null pointer to a non--null \verb2void*2.
The cast operator is overloaded to return an {\tt int}. One might
worry that ``{\tt return v}'' might result in a {\tt char}, but
the compiler knows to convert the {\tt char} into an {\tt int}.

Here are some examples of how Boolean is used:
\begin{verbatim}
Boolean b1(Boolean::True);        //calls Boolean(int)
Boolean b2(3);                    //calls Boolean(int)
int* pI=new int(3);               //pI points to an integer initialized to 3
Boolean b3(pI);                   //calls Boolean(void*)
Boolean b4(3.0);                  //calls Boolean(float)
\end{verbatim}

\centerline{\bf Built--In Boolean Type}
C++ has a built--in Boolean type called {\tt bool}. This is a relatively
new feature of C++, so your book doesn't mention it, but it's described
on page 71 of Stroustrup (3rd edition). A {\tt bool} has one of
two values: {\it true} or {\it false}. A {\tt bool} has the same
status as {\tt double} or {\tt int} or {\tt float}; it's a built--in
type. So you don't need a Boolean include file if you use {\tt bool}. 
A Boolean is used to express the results of logical operations. For
example:
\begin{verbatim}
void f(int a, int b)
  {
   bool b1=a==b;       
   //....
  }
\end{verbatim}
If {\tt a} and {\tt b} have the same value, {\tt b1} becomes 
{\it true}; otherwise {\tt b1} is {\it false}. 

A function that tests for some condition often returns a {\tt bool}.
For example:
\begin{verbatim}
  bool greater(int a, int b) {return a>b;}
\end{verbatim}
By definition, {\it true} has the value 1 when converted to an integer
and {\it false} has the value 0. Conversely, integers can be implicitly
converted to {\tt bool} values: nonzero integers convert to {\it true}
and 0 converts to {\it false}. For example:
\begin{verbatim}
  bool b = 8;       //bool(8) is true, so b becomes true
  int i = true;     //int(true) is 1, so i=1
\end{verbatim}
In arithmetic and logical expressions, {\tt bool}s are converted to
{\tt int}s; integer arithmetic and logical operations are performed
on the converted values. If the result is converted back to {\tt bool},
a 0 is converted to {\it false} and a nonzero value is converted to
{\it true}.
\begin{verbatim}
   bool a = true;
   bool b = true;
   bool x = a + b;    //a+b is 2, so x=true
   bool y = a|b;      //a|b=1, so y=true
\end{verbatim}
A pointer can be implicitly converted to a {\tt bool}. A nonzero pointer
converts to a {\it true}; zero--valued pointers convert to {\it false}.

The Boolean class defined by Barton and Nackman has the line
\begin{verbatim}
    enum constants{ false = 0, true = 1 };
\end{verbatim}
This won't compile because ``{\tt false}'' and ``{\tt true}'' are
already defined by the built--in {\tt bool}. So if you change ``{\tt false}''
to {\tt False} and ``{\tt true}'' to {\tt True} everywhere in Boolean.h
and Boolean.C, it compiles just fine.
 
\end{document}
