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 for illustrating function overloading in adding the distance between objects
Suryateja Pericherla Categories: Classes and Objects. No Comments on CPP program for illustrating function overloading in adding the distance between objects
3.3
(10)

In this article we will learn to implement a CPP program for illustrating function overloading in adding the distance between objects. A C++ program is provided below for adding the distance between objects using function overloading.

 

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

 

Now we overload the add function for adding two distance objects. 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;
		}
		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();
	d3.add(&d1, &d2);
	d3.get_distance();
	return 0;
}

 

Input and output for the above program are a follows:

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

 

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.


Leave a Reply

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

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory