Classes Objects

1. AIM: Create a Distance class with:
  • feet and inches as data members
  • member function to input distance
  • member function to output distance
  • member function to add two distance objects
Write a main function to create objects of DISTANCE class. Input two distances and output the sum.
SOURCE CODE:
#include<math.h>
#include<iostream>
using namespace std;
class Distance
{
    float feet,inch;
    public: Distance()
    {
        feet=0.0;
        inch=0.0;
    }
    void read_dist();
    void display_dist();
    void add(Distance , Distance);
};
void Distance::read_dist()
{
    cout<<"Enter distance(feet and inches):";
    cin>>feet>>inch;
}
void Distance::display_dist()
{
    cout<<"Distance Feet:"<<feet<<", Inches:"<<inch<<endl;
}
void Distance::add(Distance x,Distance y)
{
    inch=x.inch+y.inch;
    feet=x.feet+y.feet;
    if(inch>=12.0)
    {
        feet=x.feet+y.feet+(inch/12.0);
        inch=(int)inch%12;
    }
}
int main()
{
    Distance d1,d2,d3;
    cout<<"Enter first measure:\n";
    d1.read_dist();
    cout<<"Enter second measure:\n";
    d2.read_dist();
    d3.add(d1,d2);
    d3.display_dist();
}
OUTPUT:
Enter first measure:
Enter distance(feet and inches):
5
9
Enter second measure:
Enter distance(feet and inches):
7
6
Distance Feet:13.25, Inches:3

B. AIM: Write a C++ Program to illustrate the use of Constructors and Destructors (use the above program.)
SOURCE CODE:
#include using namespace std; #include<math.h>
#include<iostream>
using namespace std;
class Distance
{
    int feet,inch;
    public: Distance()
    {
        feet=0;
        inch=0;
    cout<<"Default Constructor"<;      }
     Distance(int f,int i)
     {
       feet=f;
       inches=i;
       cout<<"Argument Constructor"<      }
     void outputDistance()
     {
     cout<<"Feet="<     
}
    };
    int main()
    {
     Distance d1(2,9),d2(2,9);
     Distance d3;
     d3.addDistances(d1,d2);
     return 0;
    }
OUTPUT:
Argument Constructor
Argument Constructor
Default Constructor
Feet=5, Inches=6
Destructor
Destructor
Destructor
Destructor
Destructor

No comments:

Post a Comment