C++ | Friend function 9

Question:3
Class Distance (m and cm)
Declare a class named distance with attributes as m and cm. Take input for two distances calculate and display their sum (Without using the friend function).
Sol:

#include<iostream>
using namespace std;
class distance1
{
	private:
		int m,cm;
	public:
		void read();
		void show();
		distance1 add(distance1 d);
};
void distance1::read()
{
	cout<<"Enter m and cm ";
	cin>>m>>cm;
}
void distance1::show()
{
	cout<<m<<" m "<<cm<<" cm"<<endl;
}
distance1 distance1::add(distance1 d)
{
	distance1 t;
	t.m=m+d.m;
	t.cm=cm+d.cm;
	if(t.cm>=100)
	{
		t.m=t.m+t.cm/100;
		t.cm=t.cm%100;
	}
	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 m and cm 25 50
Enter m and cm 45 60
25 m 50 cm
45 m 60 cm
71 m 10 cm

Question:4
Class Distance (km, m ,cm)
Declare a class named distance with attributes as m and cm. Take input for two distances calculate and display their sum (Without using the friend function).
Sol:

#include<iostream>
using namespace std;
class distance1
{
	private:
		int km,m,cm;
	public:
		void read();
		void show();
		distance1 add(distance1 d);
};
void distance1::read()
{
	cout<<"Enter km, m and cm ";
	cin>>km>>m>>cm;
}
void distance1::show()
{
	cout<<km<<" km "<<m<<" m "<<cm<<" cm"<<endl;
}
distance1 distance1::add(distance1 d)
{
	distance1 t;
	t.km=km+d.km;
	t.m=m+d.m;
	t.cm=cm+d.cm;
	
	if(t.cm>=100)
	{
		t.m=t.m+t.cm/100;
		t.cm=t.cm%100;
	}
        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, m and cm 5 600 25
Enter km, m and cm 8 800 80
5 km 600 m 25 cm
8 km 800 m 80 cm
14 km 401 m 5 cm