C++ Lecture-21
C++ Lecture-21
02
LECTURE 23
04
Today’s Agenda
01 Adding 2 Objects of a Class
We have to create 3 objects, let say D1, D2, and D3 objects of class
Distance having 2 data members named feet and inches and D3 will
store the sum of feet and inches of D1 and D2.
Sample Output:-
D1
feet: 10 .
inches: 8 There are 4 ways to
D2
feet: 9 write a solution to
inches: 7 the given problem
D3
feet: 19 => 20
inches: 15 => 3
First Variety
#include <iostream>
void Distance::add(const Distance & P, const Distance & Q)
using namespace std; D1 P D2 {
feet = P.feet + Q.feet;
class Distance feet 8 feet 7 inches = P.inches + Q.inches;
{ if(inches >= 12)
private:
inches 11 inches
{ D3
int feet; 9 feet = feet + inches / 12;
int inches; inches = inches % 12;
public: } feet 15 16
void get() }
{
cout<<"Enter feet and inches: "; int main()
inches 20 8
cin>>feet>>inches; {
} Distance D1, D2, D3;
void show() D1.get();
{ D2.get();
cout<<feet<<", "<<inches<<endl; D3.add(D1, D2);
} D1.show();
void add(const Distance &, const Distance &); D2.show();
}; D3.show();
return 0;
}.
Output of The Previous Code
Output
Output
Output
#include <iostream> void add(const Distance & P, const Distance & Q, Distance & Temp)
{
using namespace std; D1 D2 Temp.feet = P.feet + Q.feet;
Temp.inches = P.inches + Q.inches;
class Distance feet 10 feet 9 if(Temp.inches >= 12)
{ {
private: Temp.feet = Temp.feet + Temp.inches / 12; D3
int feet, inches; inches 8 inches 7 Temp.inches = Temp.inches % 12;
public: }
void get() } feet 20
{
cout<<"Enter feet and inches: "; int main()
cin>>feet>>inches; {
inches 3
} Distance D1, D2, D3;
void show() D1.get();
{ D2.get();
cout<<feet<<", "<<inches<<endl; add(D1, D2, D3);
} D1.show();
friend void add(const Distance &, const Distance &, Distance &); D2.show();
}; D3.show();
return 0;
}
Output of The Previous Code
Output
Thank you