Pass Object as Function Argument and Return Object


In C++ we can pass object as a function argument and also return an object from the function.
An object can be passed to the function using two methods:
(1) Call By value: In which copy of the object is passed to the function.
(2) Call By reference: In which an address of the object is passed to the function.

     

Example:
#include<iostream.h>
class Demo
{
int a,b;
public:
Demo()
{
a=0;
b=0;
}
Demo(int x, int y)
{
a=x;
b=y;
}
void display()
{
cout<<"A="<<a<<endl<<"B="<<b<<endl;
}
Demo sum(Demo D2);
};
Demo Demo::sum(Demo D2)
{
Demo D3;
D3.a = a + D2.a;
D3.b = b + D2.b;
return D3;
}
int main()
{
Demo B1(1,2);
Demo B2(3,4);
Demo B3;
B3 =B1.sum(B2);
B3.display();
return 0;
}
Output:
A=4
B=6

Above program performs the addition of data member of two objects and store it in the third object.
Consider the function defined inside class:
Demo sum(Demo D2);
It accepts one object of the class Demo as an argument and returns an object to the calling function.
When we call the function using following statement:
B3 =B1.sum(B2);
Data member of object B1 is passed to the function implicitly while data member of object B2 is passed to the function explicitly. After performing addition of data member of two objects B1 and B2 it will store it in the data member of third object and return that object.

Download Projects


Download Programs