Page 146 - DCAP404 _Object Oriented Programming
P. 146

Unit 7: Operator Overloading




          will not evaluate all three operations and will stop after a false one is found. This behavior does  Notes
          not apply to operators that are overloaded by the programmer.
          Even the simplest C++ application, like a “hello world” program, is using overloaded operators.
          This is due to the use of this technique almost everywhere in the standard library (STL). Actually
          the most basic operations in C++ are done with overloaded operators, the IO(input/output)
          operators are overloaded versions of shift operators(<<, >>). Their use comes naturally to many
          beginning programmers, but their implementation is not straightforward. However a general
          format for overloading the input/output operators must be known by any C++ developer. We
          will apply this general form to manage the input/output for our Complex class:

          friend ostream &operator<<(ostream &out, Complex c)     //output
          {
                          out<<“real  part:  “<<real<<“\n”;
                          out<<“imag  part:  “<<imag<<“\n”;
                  return out;

          }
          friend istream &operator>>(istream &in, Complex &c)     //input
          {
                          cout<<“enter  real  part:\n”;
                  in>>c.real;
                          cout<<“enter  imag  part:  \n”;
                  in>>c.imag;
                  return in;

          }



             Notes  Note that the use of the friend keyword in order to access the private members in
             the above implementations. The main distinction between  them is that the operator>>
             may encounter unexpected errors for incorrect input, which will make it fail sometimes
             because we haven’t handled the errors correctly.
          A important  trick that can be seen in this general way of  overloading IO  is the  returning
          reference for istream/ostream which is needed in order to use them in a recursive manner:
          Complex  a(2,3);
          Complex  b(5.3,6);
          cout<<a<<b;

          Self Assessment

          Fill in the blanks:

          1.   The ……………………….. operator works by giving the value of one variable to another
               variable of the same type or closely similar.
          2.   Operators are overloaded in C++ by creating operator functions either as a member or as
               a ……………………….. of a class.



                                           LOVELY PROFESSIONAL UNIVERSITY                                   139
   141   142   143   144   145   146   147   148   149   150   151