Answer to Question #272550 in C++ for ABagha

Question #272550

Create and Implement a C++ program to overload ++ operators for the class Time.

 Data members should be hour, minute and seconds.

 Set data members as zero in default constructor.

 Take one object in main to set 23:24:59 hrs.

 Display time in the given format 23:24:59 hrs.

 Overload ++ operator to make a stop watch. (i.e. that will increment seconds by 1 each

time its called)

 Make a function by name add_time() to increment seconds.

 Write a driver program to test your class.


1
Expert's answer
2021-11-28T05:25:44-0500
#include <iostream>
using namespace std;


class Time{
	//Data members should be hour, minute and seconds.
	int hour;
	int minute;
	int seconds;
public:
	//Set data members as zero in default constructor.
	Time()
	{
		this->hour = 0;
		this->minute = 0;
		this->seconds = 0;
	}
	//Take one object in main to set 23:24:59 hrs.
	Time(int hour, int minute, int seconds)
	{
		this->hour = hour;
		this->minute = minute;
		this->seconds = seconds;
	}
	//Make a function by name add_time() to increment seconds.
	void add_time()
	{
		this->seconds++;
		if(this->seconds >= 60){
			this->minute ++; 
			this->seconds = this->seconds % 60; 
		} 
		if(this->minute >= 60){
			this->hour ++; 
			this->minute  = this->minute  % 60; 
		}
		if(this->hour >= 24){
			this->hour=0;
		}
	}
	//Overload ++ operator to make a stop watch. (i.e. that will increment seconds by 1 each time its called)
	void operator++(){
		add_time();
	}


	//Display time in the given format 23:24:59 hrs.
	void display(){
		cout<< this->hour << ":" << this->minute << ":" << this->seconds<<" hrs";
	}
};


int main(){
	int hour,minute,seconds;
	cout << "Enter the first time: " << endl;
	cin>> hour >> minute >> seconds;
	Time t(hour, minute, seconds);
	t.display();
	t++;
	cout << endl<< endl;
	t.display();
	cout << endl<< endl;
	system("pause");
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS