Wednesday, February 24, 2016

C++ Program for a wall-clock implementing class, constructor and member functions.


Define a class with necessary constructor & member functions. Derive wall-clock from class adding necessary attributes. Create two objects of wall_clock clasess with all initial state to 0 or NULL.

Algorithm:
  1. start of program
  2. create a class (clock) with necessary constructor and member functions
    1. clock()                      //constructor to initialize the time to 0:0:0
    2. getdata()                //ask for time in the format of hr:min:sec
    3. add(clock t)          //for adding time
    4. display()                 //display the time
  3. create a derived class (wall_clock) inherited publicly from base class clock
  4. create instance(object) of the derived class and access the base functions to add two times (t1.add(t2));and
  5. display the final time
  6. end of program

Source Code:



#include<iostream.h>
#include<conio.h>

class clock
{
protected:
int hr,min,sec;

public:

clock()
{ hr=0;
min=0;
sec=0;
}

void getdata(int h,int m,int s)
{ hr=h;
min=m;
sec=s;
}

void add(clock t)
{
sec+=t.sec;
if(sec>=60){
sec%=60;
min++;}
min+=t.min;
if(min>=60)
{ min%=60;
hr++;
}
hr+=t.hr;
}
void display()
{ cout<<hr<<":"<<min<<":"<<sec;
}
};

class wall_clock:public clock
{
};

void main()
{ clrscr();
wall_clock t1,t2;
t1.getdata(1,1,1);
t2.getdata(2,59,59);
cout<<endl<<"time1=";
t1.display();
cout<<endl<<"time2=";
t2.display();
t1.add(t2);
cout<<endl<<"add=";
t1.display();
getch();
}

 Output:

No comments:

Post a Comment