How to make Objects As Function Arguments in C++




Like any other data type argument, object can also be passed to a function. As you know argument are passed to a function in tow ways.

* By value 
* By reference 

The following Program illustrates the calling of function by value. The program declares a class integer representing a integer variable x. Only the value of the object are passed to the function written to swap them.

# include <iostream.h>
#include <conio.h>

class integer

{
   int x;

    public

   void get data()

{
   cout << "Enter a value for x";
   cin<< x;
}

void disp()
{
   cout<< x;
}

void swap (integer a1 ,  integer a2)
{
   int temp;
   temp =  a2.x;
   a2 .x=al.x;
   al.x = temp
}
};

main();

{
   integer int1, int2;

   int1.getdata();
   
   int2.getdata();

  cout <<"\nthe value of x belonging to object int1 is ";
  int1.disp();

  cout <<"\nthe 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 swaping";

  cout <<"\nthe vaue of x belonging to object inti  is ";
  int1.disp();

  cout <<\"nthe value of x belonging to object int2 is ";
  int2.disp();

  cout<< "\n";

 getche();

}


You should see the value following output 

 Enter a value for x 15

 Enter a value for x 50

 the value of x belonging  to object int1 is 15

 the value of x belonging  to object int1 is 15

 after awapping

 the value of x belonging to object int 1 is 50

 the value of x belonging to object int 1 is 50


































0 comments:

Post a Comment