Startertutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » Programming » C++ Programming » Programs » Classes and Objects » Cpp program to create objects of distance class and add them
Suryateja Pericherla Categories: Classes and Objects. 4 Comments on Cpp program to create objects of distance class and add them
3.3
(31)

In this article we will learn to implement a Cpp program to create objects of distance class and add them. A C++ program is provided below that adds objects of distance class.

 

We create a distance class with the following:

  • feet and inches as data members
  • member function to input distance
  • member function to output distance
  • member function to add two distance objects

We create two objects of distance class and add them. Program is as follows:

#include <iostream>
using namespace std;
class Distance
{
	private:
		int feet;
		int inches;
	public:
		void set_distance()
		{
			cout<<"Enter feet: ";
			cin>>feet;
			cout<<"Enter inches: ";
			cin>>inches;
		}
		void get_distance()
		{
			cout<<"Distance is feet= "<<feet<<", inches= "<<inches<<endl;
		}
		void add(Distance d1, Distance d2)
		{
			feet = d1.feet + d2.feet;
			inches = d1.inches + d2.inches;
			feet = feet + (inches / 12);
			inches = inches % 12;
		}
};
int main()
{
	Distance d1, d2, d3;
	d1.set_distance();
	d2.set_distance();
	d3.add(d1, d2);
	d3.get_distance();
	return 0;
}

 

Input and output for the above program are as follows:

Enter feet: 3
Enter inches: 8
Enter feet: 4
Enter inches: 9
Distance is feet= 8, inches= 5

 

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


4 Comments

You can follow any responses to this entry through the RSS 2.0 feed.

wouldn’t it be inches = inches % 10;

Hello. And Bye.

Please using function type demo

Leave a Reply

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

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory