Sunday, 29 March 2015

Returning Objects From Function

Similar to sending objects as parameters to functions, it is also possible to return objects from functions. The syntax used is similar to that of returning variables from function. The return type of the function is declared as the return object type.

Sample Program

#include <iostream.h>
class add
{
int a,b;
public:
void setvalue(int x, int y)
{
a = x;
b = y;
}
add addobj(add o1, add o2)
{
o1.a = o1.a + o2.a;
o1.b = o1.b + o2.b;
return(o1);
}
void show(void)
{
cout<<a<<b<<endl;
}
};
void main()
{
add A,B,C,D;
A.setvalue(5,10);
B.setvalue(1,2);
D = C.addobj(A,B);
D.show();
A.show();
B.show();
}

Functions Returning Strings

#include <iostream.h>
#include <conio.h>
class retu
{
char name[40];
int tot;
public:
void set(void)
{
cout<<”Enter Total”;
cin>>tot;
}
char * strret(void)
{
if(tot >500)
strcpy(name,”Pass”);
else
strcpy(name,”Fail”);
return(name);
}
void display(void)
{
cout<<”Toal<<tot<<endl;
cout<<”Result”<<name<<endl;
}
};
void main()
{
retu R;
R.set();
R.display();
}

No comments:

Post a Comment