Returning Objects from Function:
An function can return object to the calling function as it can return integer, float…. values. This can be explained as following example.
An Example:
#include<iostream.h>
class distance
{
private:
int feet;
float inches;
public:
void get_distance();
distance add_distance(distance, distance);
void display_distance();
};
void distance:: get_distance()
{ cout<<"Enter Feet:\t";
cin>>feet;
cout<<"\nEnter Inches:\t";
cin>>inches; }
void distance::display_distance()
{ cout<<"The sum is:\t" ;
cout<<feet<<"\'-"<<inches<<'\"'; }
distance distance::add_distance( distance d1, distance d2)
{
distance sum;
sum.inches=d1.inches+d2.inches;
if(sum.inches>=12)
{
sum.inches-=12;
sum.feet=1;
}
sum.feet+=(d1.feet+d2.feet);
return (sum); //object return
}
void main()
{
distance first, second, result;
cout<<"\nEnter first distance\n";
first.get_distance();
cout<<"\nEnter second distance\n";
second.get_distance();
result=result.add_distance(first,second);
result.display_distance();
}
Output:
Enter first distance
Enter Feet: 3
Enter Inches: 9
Enter second distance
Enter Feet: 5
Enter Inches: 5
The sum is: 9'-2"
In this example, function add_distance() passes two objects as arguments and it returns value of type distance i.e. object of class distance. The returned object is stored in another object result in main() function.
No comments:
Post a Comment