\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}{55}

\centerline{\large{\bf LECTURE 6}}

\centerline{\bf Friends}
Two closely coupled classes often need access to each other's data
members for efficiency:
\begin{verbatim}
    class Vector;
    class Matrix;
    class Vector {  
        .  
        .
        .
        friend class Matrix;
        .  
        .
     };
\end{verbatim}
Now {\tt Matrix} can access {\tt Vector}'s private data. Without a change
in the {\tt Matrix} class definition, {\tt Vector} still can't get at
{\tt Matrix}'s private members. It doesn't
matter where the {\tt friend} declaration is; it can be in
either public or private; it has the same access to the
private and public members of the class. 

Functions can also be friends of a class. These friend functions
can be external functions or they can be members of another class.
For example,
\begin{verbatim}
    friend Point::distance(Point);
\end{verbatim}
Notice that the extended name of the function is used in the
{\tt friend} declaration. If you want a member function of class B 
to be a friend of class A, you need to define class B first 
before defining class A. Otherwise, you have to declare
all of class B a friend of class A. In other words, a
{\tt friend} declaration cannot be the first mention of a member
function.

\centerline{\bf Complex Number Class}
As an example of using friend functions, consider the following class
for complex numbers.
\begin{verbatim}
#include <iostream.h>
#ifndef COMPLEX                           //comment 2 on "include guards"
#define COMPLEX

class complex
    {
private:
    double re, im;
public:
    complex(double r = 0, double i = 0)
        : re(r), im(i)                   //Constructs re and im. Here this
                                         //this is the same as {re=r; im=i;}.
                                         //This syntax must be used to
                                         //data members that are objects of
                                         //another class (see Lecture 3).
        { }

    double real() const                  //Inline since definition of re
        { return re; }                   //and im are in the class.
    double imag() const
        { return im; }

    complex & operator += (const complex &);
// ditto for -=, *=, /=

// Friends are not member functions
    friend double real(const complex &);
    friend double imag(const complex &);

    friend complex operator + (const complex &, const complex &);
// This could be written as 
//  complex operator + (const complex &) const;

    friend complex operator + (const complex &, double);
    friend complex operator + (double, const complex &);
// ditto for -, *, /

    friend int operator == (const complex &, const complex &);
    friend int operator == (const complex &, double);
    friend int operator == (double, const complex &);
// ditto for !=

    friend istream & operator >> (istream &, complex &);
    friend ostream & operator << (ostream &, const complex &);
    };

inline complex&                            //Comment 1: Inline
complex::operator += (const complex& r)
    {
    re += r.re;
    im += r.im;
    return *this;
    }

inline complex&
complex::operator *= (const complex& r)
    {
    double f = re * r.re - im * r.im;
    im = re * r.im + im * r.re;
    re = f;
    return *this;
    }

inline double imag (const complex& x)
    { return x.imag(); }

inline double real (const complex& x)
    { return x.real(); }

//This was a friend function, but no "friend" keyword needed here:
inline complex              
operator + (const complex& x, const complex& y)
    {
    return complex(real(x) + real(y), imag(x) + imag(y));
    }

inline complex
operator + (const complex& x, double y)
    {
    return complex(real(x) + y, imag(x));
    }

inline complex
operator * (const complex& x, const complex& y)  
    {
    return complex(real(x) * real(y) - imag(x) * imag(y),
                   real(x) * imag(y) + imag(x) * real(y));
    }

inline complex
operator * (const complex& x, double y)  
    {
    return complex(real(x) * y, imag(x) * y);
    }

inline complex
operator - (const complex& x)     //minus sign is a unary operator 
                                  //(non-member function with one argument).
    {                                             
    return complex(-real(x), -imag(x));
    }

inline int
operator == (const complex& x, const complex& y)  
    {
    return real(x) == real(y) && imag(x) == imag(y);
    }

inline int
operator == (const complex& x, double y)  
    {
    return real(x) == y && imag(x) == 0;
    }

// class istream and class ostream are defined in iostream.h. Overloading
// the >> and << operators allow us to use cin >> c and cout << c. 

ostream& operator << (ostream &s, const complex &c)
   {
   s << "(" << real(c) << "," << imag(c) << ")";
   return s;
   }

istream& operator >> (istream &s, complex &c);  //see Stroustup (3rd ed) p. 621
   /*
      input formats for a complex number ("f" indicates a floating-point
      number):
               f                pure real number
               (f)              pure real number
               (f,f)            has real and imaginary parts
   */
  {
      double re = 0,  im=0;
      char ch=0;

      s >> ch;
      if(ch == '('){
        s >> re >> ch;
        if(ch == ',') s >> im >> ch;
        if(ch != ')') s.clear(ios_base::badbit);      //set state to bad
      }
      else{
           s.putback(ch);
           s >> re;
      }
      if(s) c = complex(re,im);
      return s;
   }
   
#endif
\end{verbatim}
Notice that we are using the built--in copy constructor,
the built--in operator =, and built--in destructor.
That's why they are not overloaded in the class {\tt COMPLEX}.

\centerline{\bf Comment 1: Inline}
C++ allows functions to be defined with the keyword {\it inline}.
An {\it inline function} is written like a normal function, but
it doesn't act the same. The code for an inline function expands
in place wherever the function is used. Contrast this with a normal
function. When a normal function is compiled, the code is put in
one location. Every place where the function is called, the compiler
sticks in code to jump to that place where the function is. Inline
functions are duplicated everywhere they are needed, so you don't have
to waste time calling the function. On the other hand, the executable
is smaller if the function is only in one place and doesn't exist in
multiple copies.

To inline a function, the programmer adds the keyword {\tt inline}
in front of the definition. Because the definition is necessary to
expand an inline function, you must define an inline function before 
it can be used. So inline functions should be defined in an include file.
(Conventional ``outline'' functions should not be defined in
an include file because of the danger of defining a function multiple
times. An ``outline'' function is a normal, non--inline function.) 
Inline functions are useful only for small functions. The 
disadvantage of expanding a large function inline outweighs the
small gains from inlining the function. The break--even point for
an inline function is about 3 executable lines. Even if you declare
a function to be inline, several things may force the compiler to outline
the function. For example, including any type of looping statement
(such as a {\tt for} loop) in a function usually forces it outline.
You shouldn't inline such a function anyway, because the time it
takes to execute the loop overshadows any minor gain from declaring
the function inline.

Debugging an inline function can be tricky. Because an inline function
is expanded as part of each line that calls it, you cannot single
step an inline function with the debugger. The entire inline 
function executes as a single line no matter how many lines it contains
and no matter how much havoc those lines might cause. So to debug
an inline function, change it to an outline function by removing
the keyword {\tt inline} and recompile the program. By the way,
sometimes in recompiling, it helps to remove the \verb2.o2 files.
\centerline{\bf Comment 2: Include Guards}
Notice the preprocessor commands
\begin{verbatim}
  #ifndef COMPLEX                           
  #define COMPLEX
   . . .
  #endif
\end{verbatim}
The contents of the file between \verb2#ifndef COMPLEX2 and
\verb2#endif2 are ignored by the compiler if {\tt COMPLEX}
has already been defined previously. This is an example of
the use of {\it include guards} which are often used in
header (\verb2.h2) files to prevent class definitions or
inline functions from getting \verb2#include2d twice in the
same compilation unit. Such multiple inclusions are a danger
when there are multiple header files being included in the different
\verb2.cc2 source files that make up a single program.
Let's suppose there are several \verb2.cc2 source files that 
make up a single program. If each includes only one user-constructed
header file ``\verb2myfile.h2'', the compiler will not complain of
multiple class definitions. But if \verb2myfile.h2 contains the
definition of external functions, there will be compiler errors.
It's {\it not} ok to have multiple definitions of external
nonmember functions. External functions should be defined only once
in the program. You should put the definition of external functions
in a \verb2.cc2 source file. It's not ok to include the same header file
more than once in a \verb2.cc2 source file. Sometimes one header file
includes another header file. Then there is the danger of muliple
inclusions of a header file in each of the \verb2.cc2 source files
that make up a program. Include guards can be used to prevent this. 
For example, suppose there are 2 header files:
\begin{verbatim}
//********************complex.h**********************
  #ifndef COMPLEX
  #define COMPLEX
  class complex
   {...};
  #endif
//*******************matrices.h***********************
  #include "complex.h"
  class matrix.h
  { ... };
//*******************file.cc****************************
  #include "complex.h"
  #include "matrix.h"
  main(){
   ...
  }
\end{verbatim}
The include guards prevent \verb2complex.h2 from being included more
than once in \verb2file.cc2.

\centerline{\bf More on Overloading Operators}
We introduced the concept of overloading operators in Lecture 4, 
but there is more to be said. 
Most of this class consists of overloading operators. Notice
that just because we have overloaded the operator
\verb2complex operator + (const complex &, double)2, doesn't
mean that the operator
\verb2friend complex operator + (double, const complex &)2 
has been covered. Because these two operators
have different arguments, they have to be overloaded separately.

\centerline{\it To Be or Not To Be a Member}
Operators can be implemented as nonstatic member functions or as 
non--member functions. We can see examples of both in the {\tt complex}
class. The {\tt friend} functions are nonmember functions.
One should keep in mind that
{\tt this} is the hidden first argument to all nonstatic member functions.
So when an operator is implemented as a nonstatic member function, 
it has one less explicit argument compared to the equivalent nonmember
function. For example, the following are equivalent. You only need one of them.
\begin{verbatim}
complex operator + (const complex &, const complex &);   //nonmember function

complex
 complex::operator + (const complex &) const;            //member function
\end{verbatim}

When should you implement an operator as a member and when as a 
nonmember? The following operators must be implemented as member functions:
\begin{verbatim}
   =          Assignment

  ()          Function call

  []          Subscript
 
  ->          Class membership
\end{verbatim}
Other than the operators listed, there isn't much difference as a member
or as a nonmember, with the following exception. An operator like the
following could not be implemented as a member function:
\begin{verbatim}
  complex operator + (double, const complex &);
\end{verbatim}
Notice that the first argument is a {\tt double}, so to be a member
function, it would have to be a member of class {\tt double}. Mere
mortals cannot add operators to the intrinsic classes. Thus, operators
such as the preceding must be nonmember functions.

If you have access to the class internals, make the overloaded operator a
member of the class. This is particularly true if the operator modifies the
object upon which it operates.

\centerline{\bf Overloading ostream operator}
C++ overloads the left shift and right shift operators to perform
input and output.
The \verb2operator>>()2 is called the extractor and \verb2operator<<()2
is called the inserter. The standard {\tt iostream} library
knows how to input and output built--in types like {\tt float} and
{\tt int}, but not user-defined types like
{\tt complex}. We need to overload these operators so that
we can write things like \verb2cout << c2 where {\tt c} is a complex
number. Let's look at the declaration:
\begin{verbatim}
   ostream& operator << (ostream &s, const complex &c);
\end{verbatim}
The arguments tell us that an {\tt ostream} object will appear to the
left of \verb2<<2 and a complex number will appear to the right. In
general, when overloading the \verb2 ostream& operator <<2, the second
argument will be a {\tt const} reference to the class object. It's
{\tt const} because outputting the object's value to the screen or
a file does not change it. Thus we can write
\begin{verbatim}
   s << c
or 
   cout << c
\end{verbatim}
Notice that the {\tt ostream} object need not be called {\tt s}; 
{\tt cout} is a perfectly good {\tt ostream} object. Notice that
the \verb2operator<<()2 returns the {\tt ostream} passed to it. 
This allows the operator to be chained with other inserters in a 
single expression, i.e, this allows us to string output operators together:
\begin{verbatim}
   complex c, d, x;
   ostream s;
   s << c << d << x;
\end{verbatim}
Because the \verb2operator<<()2 binds left to right, the expression
\begin{verbatim}
      s << c << d << x;
\end{verbatim}
can be interpreted as
\begin{verbatim}
      (((s << c) << d) << x);
\end{verbatim}
The first insertion outputs the complex number {\tt c} to 
{\tt s}. The result of this expression is the object {\tt s},
which is then passed to \verb2operator<<(ostream &, const complex &)2.
It is important that this opertor return its {\tt ostream} object
so that the object can be passed to the next inserter in turn.

Overloading the extractor \verb2operator >>()2 is a little more involved
since a complex number can be entered using different formats. 
Notice that in the declaration
\begin{verbatim}
istream& operator >> (istream &s, complex &c);
\end{verbatim}
the second argument is a non--{\tt const} reference to the class
object because the class object is going to be modified by the input.
The definition associated with overloading the extractor 
comes from page 621 of Stroustrup (3rd edition):
\begin{verbatim}
  istream& operator >> (istream &s, complex &c)
   /*
      input formats for a complex number ("f" indicates a floating-point
      number):
               f                pure real number
               (f)              pure real number
               (f,f)            has real and imaginary parts
   */
  {
      double re = 0,  im=0;
      char ch=0;
    
      s >> ch;
      if(ch == '('){
        s >> re >> ch;
        if(ch == ',') s >> im >> ch;
        if(ch != ')') s.clear(ios_base::badbit);      //set state to bad
      }
      else{
           s.putback(ch);
           s >> re;
      }
      if(s) c = complex(re,im);
      return s;
   }  
\end{verbatim}
The local variable {\tt c} is initialized to avoid having 
its value accidentally
be \verb2')'2 after a failed first \verb2>>2 operation. The final 
check of the stream state ensures that the value of the argument
{\tt c} is changed only if everything went well. The operation for 
setting a stream state is called {\tt clear()} because its most common
use is to reset the state of a stream to {\tt good()}; 
\verb2ios_base::goodbit2 is the default argument value for 
\verb2ios_base::clear()2. Here, however, we are using {\tt clear()}
to set the state of {\tt s} to {\tt false}.

\centerline{\bf Complex Class}
With this complex class defined, you can do all the usual things with
complex numbers. For example,
\begin{verbatim}
  complex i(0,1), one(1,0);
  complex b,c;
  b = one/i;
  c = b * i + 2  + 3 * i;
  cout << c;
\end{verbatim}
This complex class is built into gnu C++ library.
There are other standard classes:
string, lists, queues, stacks, and random numbers. A link to a description
of one version of this library is on the class home page.

\end{document}
