Page 153 - DCAP404 _Object Oriented Programming
P. 153

Object-oriented Programming




                    Notes          7.4.1  Using Friend Function

                                   The following program is the same as previous one. The only difference is that we use a friend
                                   function to find the sum of two objects. Note that an argument is passed to this friend function.

                                   #include  <iostream.h>
                                   #include  <conio.h>
                                   class  integer
                                   {
                                   private:
                                   int  val;
                                   public:

                                   integer();
                                   integer(in  tone);
                                   friend  integer  operator+  (integer  obja,  integer  objb);
                                   void  disp();
                                   };
                                   integer::integer()
                                   {
                                          val  =  0;
                                   }

                                   integer::  integer(int  one)
                                   {
                                          val  =  one;
                                   }
                                   integer  operator+  (integer  obja,  integer  objb)
                                   {
                                          integer  objsum;

                                          objsum.val  =  obja.val  +  objb.val;
                                          return(objsum);
                                   }
                                   void  integer::disp()
                                   {
                                          cout<<  “value  =”<<  val  <<endl;
                                   }
                                   void  main()
                                   {

                                          integer  obj1(11);
                                          integer  obj2(22);



          146                               LOVELY PROFESSIONAL UNIVERSITY
   148   149   150   151   152   153   154   155   156   157   158