Google PlusFacebookTwitter

Structures – Returning Reference to a Structure

By on Mar 23, 2007 in On A Whim | 2 comments

Share On GoogleShare On FacebookShare On Twitter

/* Copyright (C) 2007 Ankur Banerjee. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. http://www.fsf.org/licensing/licenses/lgpl.html */

/* Function returning reference to a structure – WAP to add distances
entered in feet and inches */

#include <iostream.h>
#include <conio.h>

struct dist
{
int feet, inches;
} result;

void main()
{
clrscr();
dist d1, d2;
dist& add (dist&, dist&);
cout<<“Enter first distance : “;
cin>>d1.feet>>d1.inches;
cout<<“Enter the second distance : “;
cin>>d2.feet>>d2.inches;
result = add(d1, d2);
cout<<“Added result is “<<result.feet<<” feet ” <<result.inches<<” inches”<<endl;
getch();
}

dist& add (dist &a1, dist &a2)
{
dist res;
res.feet = (a1.feet + a2.feet) + ((a1.inches + a2.inches)/12);
res.inches = (a1.inches + a2.inches)%12;
return res;
}

/* Output */

Enter first distance :6
5
Enter
the second distance :8
2
Added result is 14 feet 7 inches



2 Comments

  1. supersonic_aviatrix

    April 11, 2007

    Post a Reply

    Int d2.feet etc private members?? how’re you accessing em in main?

  2. GQ

    April 11, 2007

    Post a Reply

    Er, this question is related to structures, not classes. So the question of private members doesn’t arise. Happens though sometimes, the two concepts are pretty similar, well, in at the basic level at least.

Submit a Comment

Your email address will not be published. Required fields are marked *