Page 155 - DCAP404 _Object Oriented Programming
P. 155

Object-oriented Programming




                    Notes          {
                                   private:
                                   int  m_nCents;
                                   public:
                                   Cents(int  nCents)  {  m_nCents  =  nCents;  }
                                   //  Overload  -cCents
                                   friend  Cents  operator-(const  Cents  &cCents);

                                   };
                                   //  note:  this  function  is  not  a  member  function!
                                   Cents  operator-(const  Cents  &cCents)
                                   {
                                   return  Cents(-cCents.m_nCents);
                                   }
                                   Now let’s overload the same operator using a member function instead:

                                   class  Cents
                                   {
                                   private:
                                   int  m_nCents;
                                   public:
                                   Cents(int  nCents)  {  m_nCents  =  nCents;  }
                                   //  Overload  -cCents
                                   Cents  operator-();

                                   };
                                   //  note:  this  function  is  a  member  function!
                                   Cents  Cents::operator-()
                                   {
                                           return  Cents(-m_nCents);
                                   }
                                   You’ll note that this method is pretty similar. However, the member function version of operator-
                                   doesn’t take any parameters! Where did the parameter go?  In the lesson on  the hidden this
                                   pointer, you learned that a member function has an implicit *this pointer which always points
                                   to the class object the member function is working on. The parameter we had to list explicitly in
                                   the  friend function version (which doesn’t have a *this  pointer) becomes  the implicit *this
                                   parameter in the member function version.

                                       !
                                     Caution  Remember that when C++ sees the function prototype Cents Cents::operator-();,
                                     the compiler internally converts this to Cents operator-(const Cents *this), which you will
                                     note is almost identical to our friend version Cents operator-(const Cents &cCents)!





          148                               LOVELY PROFESSIONAL UNIVERSITY
   150   151   152   153   154   155   156   157   158   159   160