Home » C+ solved programs » C++ class and object programs

C++ program to create a class to read and add two distance

In this program we will read and add two distances using class and object.

Adding two distances using class program in C++



/*C++ program to create a class to read and add two distance. */
#include  <iostream>
using namespace std;
 
class Distance
{
    private:
        int feet;
        int inch;
    public:
             Distance (); //Constructor
        void getDist  ();
        void showDist ();
        Distance addDist( Distance d2 );
        Distance subDist( Distance d2 );
};
 
Distance:: Distance ()
{
    feet = 0; inch = 0;
}
 
void Distance:: getDist()
{
    cout << "Enter Value of feets : "; cin >> feet;
    cout << "Enter value of inches : "; cin >> inch;
     
    inch = (inch >= 12) ? 12 : inch;
}
 
void Distance:: showDist()
{
    cout << endl << "\tFeets : " << feet;
    cout << endl << "\tInches: " << inch;
}
 
 
Distance Distance:: addDist( Distance d2 )
{
    Distance temp;
 
    temp.feet = feet + d2.feet;
    temp.inch = inch + d2.inch;
 
    if( temp.inch >= 12)
    {
        temp.feet++;
        temp.inch -= 12;        
    }
    return temp;    
}
 
Distance Distance:: subDist( Distance d2 )
{
    Distance temp;
 
    temp.feet = feet - d2.feet;
    temp.inch = inch - d2.inch;
 
    if( temp.inch < 0 )
    {
        temp.feet--;
        temp.inch = 12 + temp.inch;     
    }
    return temp;    
}
 
int main()
{
    Distance d1;
    Distance d2;
    Distance d3;
    Distance d4;
 
    cout << "Enter Distance1 : " << endl;
    d1.getDist();
     
    cout << "Enter Distance2 : " << endl;
    d2.getDist();
 
    d3 = d1.addDist(d2);
    d4 = d1.subDist(d2);
 
    cout << endl << "Distance1 : " ;
    d1.showDist();
 
    cout << endl << "Distance2 : " ;
    d2.showDist();
 
    cout << endl << "Distance3 : " ;
    d3.showDist();
 
    cout << endl << "Distance4 : " ;
    d4.showDist();
 
    cout << endl;         
    return 0;
}

Output

    Enter Distance1 : 
    Enter Value of feets : 10
    Enter value of inches : 7
    Enter Distance2 : 
    Enter Value of feets : 15
    Enter value of inches : 8

    Distance1 : 
	    Feets : 10
	    Inches: 7
    Distance2 : 
	    Feets : 15
	    Inches: 8
    Distance3 : 
	    Feets : 26
	    Inches: 3





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.