Functions
Returning objects
Member
Functions not only receive object as argument it can also return an object.
#include <iostream>
using namespace std;
class Sample
{
private:
int num;
public:
void set (int x)
{
num = x;
}
Sample pass(Sample
obj1, Sample obj2) //
{
Sample s4;
s4.num=obj1.num+obj2.num;
return s4;
}
}
void print()
{
cout<<num;
}
};
int main()
{
//object declarations
Sample s1;
Sample s2;
Sample s3;
//assigning values to
the data member of objects
s1.set(10);
s2.set(20);
cout<<"\n\t\t
Example program for Returning an object \n\n\n";
//passing object s1
and s2
s3=s3.pass(s1,s2);
//printing the values
of object
cout<<"\nThe
value of s1.num is ";
s1.print();
cout<<"\nThe
value of s2.num is ";
s2.print();
//printing the sum
cout<<"\nThe
sum s3.num is ";s3.print();
return 0;
}
Example program for Returning an object
The value of s1.num is 10
The value of s2.num is 20
The sum s3.num is 30
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.