Adding two objects Without using the friend function
Note: Passing objects to function and function returning an object.
Question:1
Class Distance (feet and inches)
Declare a class named distance with attributes as feet and inches. Take the input for two distances, calculate and display their sum without using the friend function.
Sol:
#include<iostream> using namespace std; class distance1 { private: int feet,inches; public: void read(); void show(); distance1 add(distance1 d); }; void distance1::read() { cout<<"Enter feet and inches "; cin>>feet>>inches; } void distance1::show() { cout<<feet<<" feet "<<inches<<" inches"<<endl; } distance1 distance1::add(distance1 d) { distance1 t; t.feet=feet+d.feet; t.inches=inches+d.inches; if(t.inches>=12) { t.feet=t.feet+t.inches/12; t.inches=t.inches%12; } return(t); } int main() { distance1 e1,e2,e3; e1.read(); e2.read(); e1.show(); e2.show(); e3=e1.add(e2); e3.show(); return(0); }
Output:
Enter feet and inches 4 10
Enter feet and inches 5 11
4 feet 10 inches
5 feet 11 inches
10 feet 9 inches
Question:2
class distance(km,m)
Declare a class named distance with attributes as km and m. Take input for two distances calculate and display their sum (Without using friend function).
Sol:
#include<iostream> using namespace std; class distance1 { private: int km,m; public: void read(); void show(); distance1 add(distance1 d); }; void distance1::read() { cout<<"Enter km and m "; cin>>km>>m; } void distance1::show() { cout<<km<<" km "<<m<<" m"<<endl; } distance1 distance1::add(distance1 d) { distance1 t; t.km=km+d.km; t.m=m+d.m; if(t.m>=1000) { t.km=t.km+t.m/1000; t.m=t.m%1000; } return(t); } int main() { distance1 e1,e2,e3; e1.read(); e2.read(); e1.show(); e2.show(); e3=e1.add(e2); e3.show(); return(0); }
Output:
Enter km and m 2 500
Enter km and m 3 800
2 km 500 m
3 km 800 m
6 km 300 m