Page 84 - DCAP404 _Object Oriented Programming
P. 84

Unit 4: Classes and Objects




                 integer  int1,  int2;                                                          Notes
                 int1.getdata();
                 int2.getdata();
                 cout  <<“\n  the  value  of  x  belonging  to  object  int1  is  “;
                 int1.disp();
                 cout  <<“\n  the  value  of  x  belonging  to  object  int2  is  “;
                 int2.disp();

                 integer  int3;  .
          int3.swap(int1,  int2);  //int3  is  just  used  to  invoke  the  function
                 cout  <<“  \nafter  swapping  “;
                 cout  <<“\n  the  value  of  x  belonging  to  object  intI  is  “;
                 intl.disp();
                 cout  <<“\n  the  value  of  x  belonging  to  object  int2  is  “;
                 int2.disp()  ;

                 cout<<  “\n”;
                 getche();
          }
          You should get the following output.
          Enter a value for x 15
          Enter a value for x 50
          the value of x belonging to object int is 15

          the value of x belonging to object int2 is 50
          after swapping
          the value of x belonging to object int is 15

          the value of x belonging to object int2 is 50
          In the second method, the address of the object is passed to the function instead of a copy of the
          object. The called function directly makes changes on the actual object used in the call. As against
          the first method any manipulations made on the object inside the function will occur in  the
          actual object.


               !
             Caution  The second method is more efficient as only the address of the object is passed and
             not the entire object.

          The following Program illustrates calling of a function by reference. The program declares a
          class integer to represent the variable x and defines functions to input and display the value. The
          function written to swap the integer values of the object takes the addresses of the objects.
          #include<iostream.h>
          #include<conio.h>





                                           LOVELY PROFESSIONAL UNIVERSITY                                   77
   79   80   81   82   83   84   85   86   87   88   89