Returning Object In C++
Just as a function takes an object as its argument, it can also return an object. The following program illustrates how objects are returned. The program declares a class integer representing an integer variable x and define a function to calculate the sum of two integer values. This function finally return an object which store the sum in its data member x.
#include<iostream.h>
#include<conio.h>
class integer
{
int x;
public:
void getdata(int x1)
{
x = x1;
}
void disp()
{
cout << x;
}
integer sum(integer int2)
{
integer int3;
int3, x = x + int2.x;
return(int3);
}
};
main()
{
integer int1, int2, int3;
int1.getdata(15);
int2.getdata(25);
cout << "\nthe value of x for object int1";
int1.disp();
cout << "\nthe value of x for object int2";
int2.disp();
cout << "\nthe sum of private data values of x belonging to object int1 and
int2 is";
int3 = int1.sum(int2);
int3.disp();
getche();
}
You should see the following output from the program.
The value of x for the object int1 15
The value of x for the object int2 25
The sum of private data values of x belonging to object int1 int2 is 40
0 comments:
Post a Comment