Answer to Question #173784 in C++ for Rocky bhai

Question #173784

Declare the class Time consisting of data members hours, minutes and seconds. Invoke a null constructor Time() when an object is created, the parameterized constructor Time(hrs, min, sec) to assign values for the data members and show() member function is used to display the time information in format. Finally free the resources of data objects using destructor member function.


1
Expert's answer
2021-03-20T14:33:38-0400
#include <iostream>
#include<iomanip>
#include <stdexcept>

using namespace std;

class Time {
    private:
        int hours;
        int minutes;
        int seconds;
    public :
        Time(int hrs, int min, int sec);
        Time();
        ~Time();
        
        void validTime(int hrs, int min, int sec);
        void show();
};

Time::Time(int hrs, int min, int sec) {
    validTime(hrs, min, sec); 
    this->hours = hrs;
    this->minutes = min;
    this->seconds = sec;
}

Time::Time() {
    this->hours = 0;
    this->minutes = 0;
    this->seconds = 0;
}

Time::~Time() {

}

void Time::validTime(int hrs, int min, int sec) {
    if (hrs < 0 || hrs > 24 || min < 0 || min > 59 || sec < 0 || sec > 59) {
        throw(domain_error("Time value out of range"));
    }
}

void Time::show() {
    cout << setw(2) << setfill('0') << hours << ":"
        << setw(2) << setfill('0') << minutes << ":"
        << setw(2) << setfill('0') << seconds << "\n"; 
}

int main() {
    Time *time = new Time();

    Time *time2 = new Time(21, 5, 30);

    time->show();

    time2->show();

    delete time;

    delete time2;

    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