Answer to Question #197947 in C++ for mohib

Question #197947

Create a class called Time that has separate int member data for hours, minutes,

and seconds. One constructor should initialize this data to 0 (default constructor),

and another should initialize it to fixed values (overloaded constructor). Another

member function should display it, in hh:mm:ss (hours: minutes: seconds) format.

Also write the destructor of this class. Write the program that creates three

objects (t1, t2 and t3) of the class to display the time. Initialize t1 using default

constructor, t2 with overloaded constructor and t3 with the values of t2


1
Expert's answer
2021-05-24T10:52:45-0400
#include <iostream>

class Time {
public:
    Time()
        : hours_(0)
        , minutes_(0)
        , seconds_(0)
    {}
    
    Time(int hours, int minutes, int seconds)
        : hours_(hours)
        , minutes_(minutes)
        , seconds_(seconds)
    {}

    Time(const Time& time)
        : hours_(time.hours_)
        , minutes_(time.minutes_)
        , seconds_(time.seconds_)
    {}

    ~Time() {
        // default destructor
    }

    void Display() const {
        std::cout << (hours_ <= 9 ? "0" : "") << hours_ << ":";
        std::cout << (minutes_ <= 9 ? "0" : "") << minutes_ << ":";
        std::cout << (seconds_ <= 9 ? "0" : "") << seconds_;
    }

private:
    int hours_;
    int minutes_;
    int seconds_;
};

int main() {
    Time t1, t2(1, 10, 20), t3(t2);
    std::cout << "t1: ";
    t1.Display();
    std::cout << "\nt2: ";
    t2.Display();
    std::cout << "\nt3: ";
    t3.Display();
    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